<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="keywords" content="玖忆;文鹤;博客">
    
    <meta name="author" content="meteor">
    <!-- preconnect -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    
    
    <!--- Seo Part-->
    
    <link rel="canonical" href="https://wait-you.github.io/2023/06/06/设计模式/"/>
    <meta name="robots" content="index,follow">
    <meta name="googlebot" content="index,follow">
    <meta name="revisit-after" content="1 days">
    
        <meta name="description" content="# 1，设计模式 # 1.1 软件设计模式的产生背景 &quot;设计模式&quot; 最初并不是出现在软件设计中，而是被用于建筑领域的设计中。 1977 年美国著名建筑大师、加利福尼亚大学伯克利分校环境结构中心主任 克里斯托夫·亚历山大（Christopher Alexander） 在他的著作《建筑模式语言：城镇、建筑、构造》中描述了一些常见的建筑设计问题，并提出了 253 种关于对城镇、邻里、">
<meta property="og:type" content="article">
<meta property="og:title" content="设计模式">
<meta property="og:url" content="https://wait-you.github.io/2023/06/06/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/index.html">
<meta property="og:site_name" content="玖忆">
<meta property="og:description" content="# 1，设计模式 # 1.1 软件设计模式的产生背景 &quot;设计模式&quot; 最初并不是出现在软件设计中，而是被用于建筑领域的设计中。 1977 年美国著名建筑大师、加利福尼亚大学伯克利分校环境结构中心主任 克里斯托夫·亚历山大（Christopher Alexander） 在他的著作《建筑模式语言：城镇、建筑、构造》中描述了一些常见的建筑设计问题，并提出了 253 种关于对城镇、邻里、">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420224700618.jpg">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/2021042022474324.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420224803841.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420224817932.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420224845698.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420224909181.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420224926483.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420224942637.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/2021042022495933.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420225015611.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420225039964.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420225133349.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420225829652.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420225857845.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420225916824.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420225304649.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420225241132.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/202104202259471.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420230021873.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420230052402.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420230134217.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420230250942.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420230327522.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420230400215.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420230428784.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420230453918.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420230516219.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420225344619.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420230558335.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420230626476.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420230646842.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420230712930.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420230740577.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/2021042023075989.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420230823544.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420225505709.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420230858629.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420230923369.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/2021042022553241.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420231045990.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420231123895.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420231153608.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/2021042022555665.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420231232717.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420225633681.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420231302277.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420231358807.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420231425763.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420225707204.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420231509643.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420231525497.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420231540386.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420231600431.jpeg">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420231623551.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420231644366.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420231706979.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420231724170.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420231753669.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420231807973.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420231934811.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420231954390.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420232023190.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420232039369.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420232053415.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420232124135.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420232203595.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420232240991.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420232317504.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420225744449.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420232437613.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420232505144.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420232536766.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420232553228.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420232619804.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420232642626.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420232705188.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/2021042023272395.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420232809922.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420232829541.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420232844936.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420232911848.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420232930473.png">
<meta property="og:image" content="http://tuchuang.wenhe9.cn/20210420232952954.png">
<meta property="article:published_time" content="2023-06-06T01:12:30.000Z">
<meta property="article:modified_time" content="2023-06-05T09:13:22.928Z">
<meta property="article:author" content="meteor">
<meta property="article:tag" content="设计模式">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://tuchuang.wenhe9.cn/20210420224700618.jpg">
    
    
    <!--- Icon Part-->
    <link rel="icon" type="image/png" href="/images/wenhe.png" sizes="192x192">
    <link rel="apple-touch-icon" sizes="180x180" href="/images/wenhe.png">
    <meta name="theme-color" content="#f1404b">
    <link rel="shortcut icon" href="/images/wenhe.png">
    <!--- Page Info-->
    
    <title>
        
            设计模式 -
        
        玖忆
    </title>
    
<link rel="stylesheet" href="/css/style.css">

    
<link rel="stylesheet" href="/assets/fonts.css">

    <!--- Font Part-->
    
    
    
    

    <!--- Inject Part-->
    
    <script id="hexo-configurations">
    let Global = window.Global || {};
    Global.hexo_config = {"hostname":"wait-you.github.io","root":"/","language":"zh-CN"};
    Global.theme_config = {"articles":{"style":{"font_size":"16px","line_height":1.5,"image_border_radius":"14px","image_alignment":"center","image_caption":false,"link_icon":true},"word_count":{"enable":true,"count":true,"min2read":true},"author_label":{"enable":true,"auto":false,"list":[]},"code_block":{"copy":true,"style":"mac","font":{"enable":false,"family":null,"url":null}},"toc":{"enable":true,"max_depth":3,"number":false,"expand":true,"init_open":true},"copyright":true,"lazyload":true,"recommendation":{"enable":false,"title":"推荐阅读","limit":3,"placeholder":"http://tuchuang.wenhe9.cn/default-bg.jpg","skip_dirs":[]}},"colors":{"primary":"#f1404b","secondary":null},"global":{"fonts":{"chinese":{"enable":false,"family":null,"url":null},"english":{"enable":false,"family":null,"url":null}},"content_max_width":"1000px","sidebar_width":"210px","hover":{"shadow":true,"scale":false},"scroll_progress":{"bar":true,"percentage":true},"busuanzi_counter":{"enable":true,"site_pv":true,"site_uv":true,"post_pv":true},"pjax":true,"open_graph":true,"google_analytics":{"enable":false,"id":null}},"home_banner":{"enable":true,"style":"static","image":{"light":"http://tuchuang.wenhe9.cn/default-bg.jpg","dark":"http://tuchuang.wenhe9.cn/default-bg.jpg"},"title":"玖忆","subtitle":{"text":["我本微末凡尘、可也心向天空"],"hitokoto":{"enable":false,"api":"https://v1.hitokoto.cn"},"typing_speed":100,"backing_speed":80,"starting_delay":500,"backing_delay":1500,"loop":true,"smart_backspace":true},"text_color":{"light":"#fff","dark":"#d1d1b6"},"text_style":{"title_size":"2.8rem","subtitle_size":"1.5rem","line_height":1.2},"custom_font":{"enable":false,"family":null,"url":null},"social_links":{"enable":true,"links":{"github":"https://gitee.com/du-jinliang","instagram":null,"zhihu":null,"twitter":null,"email":"dujinliang9@163.com"}}},"plugins":{"feed":{"enable":false},"aplayer":{"enable":false,"type":"fixed","audios":[{"name":null,"artist":null,"url":null,"cover":null}]},"mermaid":{"enable":false,"version":"9.3.0"}},"version":"2.1.4","navbar":{"auto_hide":true,"color":{"left":"#f78736","right":"#367df7","transparency":35},"links":{"Home":{"path":"/","icon":"fa-regular fa-house"}},"search":{"enable":false,"preload":true}},"page_templates":{"friends_column":2,"tags_style":"blur"},"home":{"sidebar":{"enable":true,"position":"left","first_item":"menu","announcement":null,"links":null},"article_date_format":"auto","categories":{"enable":true,"limit":3},"tags":{"enable":true,"limit":3}}};
    Global.language_ago = {"second":"%s 秒前","minute":"%s 分钟前","hour":"%s 小时前","day":"%s 天前","week":"%s 周前","month":"%s 个月前","year":"%s 年前"};
    Global.data_config = {"masonry":false};
  </script>
    
    <!--- Fontawesome Part-->
    
<link rel="stylesheet" href="/fontawesome/fontawesome.min.css">

    
<link rel="stylesheet" href="/fontawesome/brands.min.css">

    
<link rel="stylesheet" href="/fontawesome/solid.min.css">

    
<link rel="stylesheet" href="/fontawesome/regular.min.css">

    
    
    
    
<meta name="generator" content="Hexo 6.3.0"></head>


<body>
<div class="progress-bar-container">
    
        <span class="scroll-progress-bar"></span>
    

    
        <span class="pjax-progress-bar"></span>
        <span class="pjax-progress-icon">
            <i class="fa-solid fa-circle-notch fa-spin"></i>
        </span>
    
</div>


<main class="page-container">

    

    <div class="main-content-container">

        <div class="main-content-header">
            <header class="navbar-container">
    
    <div class="navbar-content">
        <div class="left">
            
            <a class="logo-title" href="/">
                
                玖忆
                
            </a>
        </div>

        <div class="right">
            <!-- PC -->
            <div class="desktop">
                <ul class="navbar-list">
                    
                        
                            <li class="navbar-item">
                                <!-- Menu -->
                                <a class="" 
                                    href="/"  >
                                    
                                        
                                            <i class="fa-regular fa-house"></i>
                                        
                                        首页
                                    
                                </a>
                                <!-- Submenu -->
                                
                            </li>
                    
                    
                </ul>
            </div>
            <!-- Mobile -->
            <div class="mobile">
                
                <div class="icon-item navbar-bar">
                    <div class="navbar-bar-middle"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- Mobile drawer -->
    <div class="navbar-drawer">
        <ul class="drawer-navbar-list">
            
                
                    <li class="drawer-navbar-item flex-center">
                        <a class="" 
                        href="/"  >
                             
                                
                                    <i class="fa-regular fa-house"></i>
                                
                                首页
                            
                        </a>
                    </li>
                    <!-- Submenu -->
                    
            

        </ul>
    </div>

    <div class="window-mask"></div>

</header>


        </div>

        <div class="main-content-body">

            

            <div class="main-content">

                
                    <div class="fade-in-down-animation">
    <div class="post-page-container">
        <div class="article-content-container">

            
            
                <div class="article-title">
                    <h1 class="article-title-regular">设计模式</h1>
                </div>
            
                
            

            
                <div class="article-header">
                    <div class="avatar">
                        <img src="/images/wenhe.png">
                    </div>
                    <div class="info">
                        <div class="author">
                            <span class="name">meteor</span>
                            
                                <span class="author-label">Lv3</span>
                            
                        </div>
                        <div class="meta-info">
                            <div class="article-meta-info">
    <span class="article-date article-meta-item">
        <i class="fa-regular fa-pen-fancy"></i>&nbsp;
        <span class="desktop">2023-06-05 17:12:30</span>
        <span class="mobile">2023-06-05 17:12</span>
        <span class="hover-info">创建</span>
    </span>
    
        <span class="article-date article-meta-item">
            <i class="fa-regular fa-wrench"></i>&nbsp;
            <span class="desktop">2023-06-05 01:13:22</span>
            <span class="mobile">2023-06-05 01:13</span>
            <span class="hover-info">更新</span>
        </span>
    

    
        <span class="article-categories article-meta-item">
            <i class="fa-regular fa-folders"></i>&nbsp;
            <ul>
                
                    <li>
                        <a href="/categories/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">设计模式</a>&nbsp;
                    </li>
                
            </ul>
        </span>
    
    
        <span class="article-tags article-meta-item">
            <i class="fa-regular fa-tags"></i>&nbsp;
            <ul>
                
                    <li>
                        <a href="/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">设计模式</a>&nbsp;
                    </li>
                
            </ul>
        </span>
    

    
    
    
    
        <span class="article-pv article-meta-item">
            <i class="fa-regular fa-eye"></i>&nbsp;<span id="busuanzi_value_page_pv"></span>
        </span>
    
</div>

                        </div>
                    </div>
                </div>
            

            <div class="article-content markdown-body">
                <h1 id="1设计模式"><a class="markdownIt-Anchor" href="#1设计模式">#</a> 1，设计模式</h1>
<h2 id="11-软件设计模式的产生背景"><a class="markdownIt-Anchor" href="#11-软件设计模式的产生背景">#</a> 1.1 软件设计模式的产生背景</h2>
<p>&quot;设计模式&quot; 最初并不是出现在软件设计中，而是被用于建筑领域的设计中。</p>
<p>1977 年美国著名建筑大师、加利福尼亚大学伯克利分校环境结构中心主任 <code>克里斯托夫·亚历山大（Christopher Alexander）</code> 在他的著作《建筑模式语言：城镇、建筑、构造》中描述了一些常见的建筑设计问题，并提出了 253 种关于对城镇、邻里、住宅、花园和房间等进行设计的基本模式。</p>
<p>1990 年软件工程界开始研讨设计模式的话题，后来召开了多次关于设计模式的研讨会。直到 1995 年，艾瑞克・伽马（ErichGamma）、理査德・海尔姆（Richard Helm）、拉尔夫・约翰森（Ralph Johnson）、约翰・威利斯迪斯（John Vlissides）等 4 位作者合作出版了《设计模式：可复用面向对象软件的基础》一书，在此书中收录了 23 个设计模式，这是设计模式领域里程碑的事件，导致了软件设计模式的突破。这 4 位作者在软件开发领域里也以他们的 “四人组”（Gang of Four，GoF）著称。</p>
<h2 id="12-软件设计模式的概念"><a class="markdownIt-Anchor" href="#12-软件设计模式的概念">#</a> 1.2 软件设计模式的概念</h2>
<p>软件设计模式（Software Design Pattern），又称设计模式，是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。它描述了在软件设计过程中的一些不断重复发生的问题，以及该问题的解决方案。也就是说，它是解决特定问题的一系列套路，是前辈们的代码设计经验的总结，具有一定的普遍性，可以反复使用。</p>
<h2 id="13-学习设计模式的必要性"><a class="markdownIt-Anchor" href="#13-学习设计模式的必要性">#</a> 1.3 学习设计模式的必要性</h2>
<p>设计模式的本质是面向对象设计原则的实际运用，是对类的封装性、继承性和多态性以及类的关联关系和组合关系的充分理解。</p>
<p>正确使用设计模式具有以下优点。</p>
<ul>
<li>可以提高程序员的思维能力、编程能力和设计能力。</li>
<li>使程序设计更加标准化、代码编制更加工程化，使软件开发效率大大提高，从而缩短软件的开发周期。</li>
<li>使设计的代码可重用性高、可读性强、可靠性高、灵活性好、可维护性强。</li>
</ul>
<h2 id="14-设计模式分类"><a class="markdownIt-Anchor" href="#14-设计模式分类">#</a> 1.4 设计模式分类</h2>
<ul>
<li>
<p><strong>创建型模式</strong></p>
<p>用于描述 “怎样创建对象”，它的主要特点是 “将对象的创建与使用分离”。GoF（四人组）书中提供了单例、原型、工厂方法、抽象工厂、建造者等 5 种创建型模式。</p>
</li>
<li>
<p><strong>结构型模式</strong></p>
<p>用于描述如何将类或对象按某种布局组成更大的结构，GoF（四人组）书中提供了代理、适配器、桥接、装饰、外观、享元、组合等 7 种结构型模式。</p>
</li>
<li>
<p><strong>行为型模式</strong></p>
<p>用于描述类或对象之间怎样相互协作共同完成单个对象无法单独完成的任务，以及怎样分配职责。GoF（四人组）书中提供了模板方法、策略、命令、职责链、状态、观察者、中介者、迭代器、访问者、备忘录、解释器等 11 种行为型模式。</p>
</li>
</ul>
<h1 id="2uml图"><a class="markdownIt-Anchor" href="#2uml图">#</a> 2，UML 图</h1>
<p>统一建模语言（Unified Modeling Language，UML）是用来设计软件的可视化建模语言。它的特点是简单、统一、图形化、能表达软件设计中的动态与静态信息。</p>
<p>UML 从目标系统的不同角度出发，定义了用例图、类图、对象图、状态图、活动图、时序图、协作图、构件图、部署图等 9 种图。</p>
<h2 id="21-类图概述"><a class="markdownIt-Anchor" href="#21-类图概述">#</a> 2.1 类图概述</h2>
<p>类图 (Class diagram) 是显示了模型的静态结构，特别是模型中存在的类、类的内部结构以及它们与其他类的关系等。类图不显示暂时性的信息。类图是面向对象建模的主要组成部分。</p>
<h2 id="22-类图的作用"><a class="markdownIt-Anchor" href="#22-类图的作用">#</a> 2.2 类图的作用</h2>
<ul>
<li>在软件工程中，类图是一种静态的结构图，描述了系统的类的集合，类的属性和类之间的关系，可以简化了人们对系统的理解；</li>
<li>类图是系统分析和设计阶段的重要产物，是系统编码和测试的重要模型。</li>
</ul>
<h2 id="23-类图表示法"><a class="markdownIt-Anchor" href="#23-类图表示法">#</a> 2.3 类图表示法</h2>
<h3 id="231-类的表示方式"><a class="markdownIt-Anchor" href="#231-类的表示方式">#</a> 2.3.1 类的表示方式</h3>
<p>在 UML 类图中，类使用包含类名、属性 (field) 和方法 (method) 且带有分割线的矩形来表示，比如下图表示一个 Employee 类，它包含 name,age 和 address 这 3 个属性，以及 work () 方法。</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420224700618.jpg"
                      alt="在这里插入图片描述"
                ></p>
<p>属性 / 方法名称前加的加号和减号表示了这个属性 / 方法的可见性，UML 类图中表示可见性的符号有三种：</p>
<ul>
<li>
<p>+：表示 public</p>
</li>
<li>
<p>-：表示 private</p>
</li>
<li>
<p>#：表示 protected</p>
</li>
</ul>
<p>属性的完整表示方式是： <strong>可见性  名称 ：类型 [= 缺省值]</strong></p>
<p>方法的完整表示方式是： <strong>可见性  名称 (参数列表) [ ： 返回类型]</strong></p>
<blockquote>
<p>注意：</p>
<p>1，中括号中的内容表示是可选的</p>
<p>2，也有将类型放在变量名前面，返回值类型放在方法名前面</p>
</blockquote>
<p><strong>举个栗子：</strong></p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/2021042022474324.png"
                      alt="在这里插入图片描述"
                ></p>
<p>上图 Demo 类定义了三个方法：</p>
<ul>
<li>method () 方法：修饰符为 public，没有参数，没有返回值。</li>
<li>method1 () 方法：修饰符为 private，没有参数，返回值类型为 String。</li>
<li>method2 () 方法：修饰符为 protected，接收两个参数，第一个参数类型为 int，第二个参数类型为 String，返回值类型是 int。</li>
</ul>
<h3 id="232-类与类之间关系的表示方式"><a class="markdownIt-Anchor" href="#232-类与类之间关系的表示方式">#</a> 2.3.2 类与类之间关系的表示方式</h3>
<h4 id="2321-关联关系"><a class="markdownIt-Anchor" href="#2321-关联关系">#</a> 2.3.2.1 关联关系</h4>
<p>关联关系是对象之间的一种引用关系，用于表示一类对象与另一类对象之间的联系，如老师和学生、师傅和徒弟、丈夫和妻子等。关联关系是类与类之间最常用的一种关系，分为一般关联关系、聚合关系和组合关系。我们先介绍一般关联。</p>
<p>关联又可以分为单向关联，双向关联，自关联。</p>
<p><strong>1，单向关联</strong></p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420224803841.png"
                      alt="在这里插入图片描述"
                ></p>
<p>在 UML 类图中单向关联用一个带箭头的实线表示。上图表示每个顾客都有一个地址，这通过让 Customer 类持有一个类型为 Address 的成员变量类实现。</p>
<p><strong>2，双向关联</strong></p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420224817932.png"
                      alt="在这里插入图片描述"
                ></p>
<p>从上图中我们很容易看出，所谓的双向关联就是双方各自持有对方类型的成员变量。</p>
<p>在 UML 类图中，双向关联用一个不带箭头的直线表示。上图中在 Customer 类中维护一个 List&lt;Product&gt;，表示一个顾客可以购买多个商品；在 Product 类中维护一个 Customer 类型的成员变量表示这个产品被哪个顾客所购买。</p>
<p><strong>3，自关联</strong></p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420224845698.png"
                      alt="在这里插入图片描述"
                ></p>
<p>自关联在 UML 类图中用一个带有箭头且指向自身的线表示。上图的意思就是 Node 类包含类型为 Node 的成员变量，也就是 “自己包含自己”。</p>
<h4 id="2322-聚合关系"><a class="markdownIt-Anchor" href="#2322-聚合关系">#</a> 2.3.2.2 聚合关系</h4>
<p>聚合关系是关联关系的一种，是强关联关系，是整体和部分之间的关系。</p>
<p>聚合关系也是通过成员对象来实现的，其中成员对象是整体对象的一部分，但是成员对象可以脱离整体对象而独立存在。例如，学校与老师的关系，学校包含老师，但如果学校停办了，老师依然存在。</p>
<p>在 UML 类图中，聚合关系可以用带空心菱形的实线来表示，菱形指向整体。下图所示是大学和教师的关系图：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420224909181.png"
                      alt="在这里插入图片描述"
                ></p>
<h4 id="2323-组合关系"><a class="markdownIt-Anchor" href="#2323-组合关系">#</a> 2.3.2.3 组合关系</h4>
<p>组合表示类之间的整体与部分的关系，但它是一种更强烈的聚合关系。</p>
<p>在组合关系中，整体对象可以控制部分对象的生命周期，一旦整体对象不存在，部分对象也将不存在，部分对象不能脱离整体对象而存在。例如，头和嘴的关系，没有了头，嘴也就不存在了。</p>
<p>在 UML 类图中，组合关系用带实心菱形的实线来表示，菱形指向整体。下图所示是头和嘴的关系图：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420224926483.png"
                      alt="在这里插入图片描述"
                ></p>
<h4 id="2324-依赖关系"><a class="markdownIt-Anchor" href="#2324-依赖关系">#</a> 2.3.2.4 依赖关系</h4>
<p>依赖关系是一种使用关系，它是对象之间耦合度最弱的一种关联方式，是临时性的关联。在代码中，某个类的方法通过局部变量、方法的参数或者对静态方法的调用来访问另一个类（被依赖类）中的某些方法来完成一些职责。</p>
<p>在 UML 类图中，依赖关系使用带箭头的虚线来表示，箭头从使用类指向被依赖的类。下图所示是司机和汽车的关系图，司机驾驶汽车：</p>
<p>[外<img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420224942637.png"
                      alt="在这里插入图片描述"
                ></p>
<h4 id="2325-继承关系"><a class="markdownIt-Anchor" href="#2325-继承关系">#</a> 2.3.2.5 继承关系</h4>
<p>继承关系是对象之间耦合度最大的一种关系，表示一般与特殊的关系，是父类与子类之间的关系，是一种继承关系。</p>
<p>在 UML 类图中，泛化关系用带空心三角箭头的实线来表示，箭头从子类指向父类。在代码实现时，使用面向对象的继承机制来实现泛化关系。例如，Student 类和 Teacher 类都是 Person 类的子类，其类图如下图所示：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/2021042022495933.png"
                      alt="在这里插入图片描述"
                ></p>
<h4 id="2326-实现关系"><a class="markdownIt-Anchor" href="#2326-实现关系">#</a> 2.3.2.6 实现关系</h4>
<p>实现关系是接口与实现类之间的关系。在这种关系中，类实现了接口，类中的操作实现了接口中所声明的所有的抽象操作。</p>
<p>在 UML 类图中，实现关系使用带空心三角箭头的虚线来表示，箭头从实现类指向接口。例如，汽车和船实现了交通工具，其类图如图 9 所示。</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420225015611.png"
                      alt="在这里插入图片描述"
                ></p>
<h1 id="3软件设计原则"><a class="markdownIt-Anchor" href="#3软件设计原则">#</a> 3，软件设计原则</h1>
<p>在软件开发中，为了提高软件系统的可维护性和可复用性，增加软件的可扩展性和灵活性，程序员要尽量根据 6 条原则来开发程序，从而提高软件开发效率、节约软件开发成本和维护成本。</p>
<h2 id="31-开闭原则"><a class="markdownIt-Anchor" href="#31-开闭原则">#</a> 3.1 开闭原则</h2>
<p><strong>对扩展开放，对修改关闭</strong>。在程序需要进行拓展的时候，不能去修改原有的代码，实现一个热插拔的效果。简言之，是为了使程序的扩展性好，易于维护和升级。</p>
<p>想要达到这样的效果，我们需要使用接口和抽象类。</p>
<p>因为抽象灵活性好，适应性广，只要抽象的合理，可以基本保持软件架构的稳定。而软件中易变的细节可以从抽象派生来的实现类来进行扩展，当软件需要发生变化时，只需要根据需求重新派生一个实现类来扩展就可以了。</p>
<p>下面以  <code>搜狗输入法</code>  的皮肤为例介绍开闭原则的应用。</p>
<p>【例】 <code>搜狗输入法</code>  的皮肤设计。</p>
<p>分析： <code>搜狗输入法</code>  的皮肤是输入法背景图片、窗口颜色和声音等元素的组合。用户可以根据自己的喜爱更换自己的输入法的皮肤，也可以从网上下载新的皮肤。这些皮肤有共同的特点，可以为其定义一个抽象类（AbstractSkin），而每个具体的皮肤（DefaultSpecificSkin 和 HeimaSpecificSkin）是其子类。用户窗体可以根据需要选择或者增加新的主题，而不需要修改原代码，所以它是满足开闭原则的。</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420225039964.png"
                      alt="在这里插入图片描述"
                ></p>
<h2 id="32-里氏代换原则"><a class="markdownIt-Anchor" href="#32-里氏代换原则">#</a> 3.2 里氏代换原则</h2>
<p>里氏代换原则是面向对象设计的基本原则之一。</p>
<p>里氏代换原则：任何基类可以出现的地方，子类一定可以出现。通俗理解：<strong>子类可以扩展父类的功能，但不能改变父类原有的功能。换句话说，子类继承父类时，除添加新的方法完成新增功能外，尽量不要重写父类的方法。</strong></p>
<p>如果通过重写父类的方法来完成新的功能，这样写起来虽然简单，但是整个继承体系的可复用性会比较差，特别是运用多态比较频繁时，程序运行出错的概率会非常大。</p>
<p>下面看一个里氏替换原则中经典的一个例子</p>
<p>【例】正方形不是长方形。</p>
<p>在数学领域里，正方形毫无疑问是长方形，它是一个长宽相等的长方形。所以，我们开发的一个与几何图形相关的软件系统，就可以顺理成章的让正方形继承自长方形。</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420225133349.png"
                      alt="在这里插入图片描述"
                ></p>
<p>代码如下：</p>
<p><strong>长方形类（Rectangle）：</strong></p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Rectangle</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">double</span> length;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">double</span> width;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="type">double</span> <span class="title function_">getLength</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> length;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setLength</span><span class="params">(<span class="type">double</span> length)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.length = length;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="type">double</span> <span class="title function_">getWidth</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> width;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setWidth</span><span class="params">(<span class="type">double</span> width)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.width = width;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><strong>正方形（Square）：</strong></p>
<p>由于正方形的长和宽相同，所以在方法 setLength 和 setWidth 中，对长度和宽度都需要赋相同值。</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Square</span> <span class="keyword">extends</span> <span class="title class_">Rectangle</span> &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setWidth</span><span class="params">(<span class="type">double</span> width)</span> &#123;</span><br><span class="line">        <span class="built_in">super</span>.setLength(width);</span><br><span class="line">        <span class="built_in">super</span>.setWidth(width);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setLength</span><span class="params">(<span class="type">double</span> length)</span> &#123;</span><br><span class="line">        <span class="built_in">super</span>.setLength(length);</span><br><span class="line">        <span class="built_in">super</span>.setWidth(length);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>类 RectangleDemo 是我们的软件系统中的一个组件，它有一个 resize 方法依赖基类 Rectangle，resize 方法是 RectandleDemo 类中的一个方法，用来实现宽度逐渐增长的效果。</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">RectangleDemo</span> &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">resize</span><span class="params">(Rectangle rectangle)</span> &#123;</span><br><span class="line">        <span class="keyword">while</span> (rectangle.getWidth() &lt;= rectangle.getLength()) &#123;</span><br><span class="line">            rectangle.setWidth(rectangle.getWidth() + <span class="number">1</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//打印长方形的长和宽</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">printLengthAndWidth</span><span class="params">(Rectangle rectangle)</span> &#123;</span><br><span class="line">        System.out.println(rectangle.getLength());</span><br><span class="line">        System.out.println(rectangle.getWidth());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">Rectangle</span> <span class="variable">rectangle</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Rectangle</span>();</span><br><span class="line">        rectangle.setLength(<span class="number">20</span>);</span><br><span class="line">        rectangle.setWidth(<span class="number">10</span>);</span><br><span class="line">        resize(rectangle);</span><br><span class="line">        printLengthAndWidth(rectangle);</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;============&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="type">Rectangle</span> <span class="variable">rectangle1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Square</span>();</span><br><span class="line">        rectangle1.setLength(<span class="number">10</span>);</span><br><span class="line">        resize(rectangle1);</span><br><span class="line">        printLengthAndWidth(rectangle1);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>我们运行一下这段代码就会发现，假如我们把一个普通长方形作为参数传入 resize 方法，就会看到长方形宽度逐渐增长的效果，当宽度大于长度，代码就会停止，这种行为的结果符合我们的预期；假如我们再把一个正方形作为参数传入 resize 方法后，就会看到正方形的宽度和长度都在不断增长，代码会一直运行下去，直至系统产生溢出错误。所以，普通的长方形是适合这段代码的，正方形不适合。<br>
我们得出结论：在 resize 方法中，Rectangle 类型的参数是不能被 Square 类型的参数所代替，如果进行了替换就得不到预期结果。因此，Square 类和 Rectangle 类之间的继承关系违反了里氏代换原则，它们之间的继承关系不成立，正方形不是长方形。</p>
<p>如何改进呢？此时我们需要重新设计他们之间的关系。抽象出来一个四边形接口 (Quadrilateral)，让 Rectangle 类和 Square 类实现 Quadrilateral 接口</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420225829652.png"
                      alt="在这里插入图片描述"
                ></p>
<h2 id="33-依赖倒转原则"><a class="markdownIt-Anchor" href="#33-依赖倒转原则">#</a> 3.3 依赖倒转原则</h2>
<p>高层模块不应该依赖低层模块，两者都应该依赖其抽象；抽象不应该依赖细节，细节应该依赖抽象。简单的说就是要求对抽象进行编程，不要对实现进行编程，这样就降低了客户与实现模块间的耦合。</p>
<p><strong>不应该依赖于具体的实现类，而依赖于该实现类的抽象父类或父接口</strong></p>
<p>下面看一个例子来理解依赖倒转原则</p>
<p>【例】组装电脑</p>
<p>现要组装一台电脑，需要配件 cpu，硬盘，内存条。只有这些配置都有了，计算机才能正常的运行。选择 cpu 有很多选择，如 Intel，AMD 等，硬盘可以选择希捷，西数等，内存条可以选择金士顿，海盗船等。</p>
<p><strong>类图如下：</strong></p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420225857845.png"
                      alt="在这里插入图片描述"
                ></p>
<p>代码如下：</p>
<p><strong>希捷硬盘类（XiJieHardDisk）:</strong></p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">XiJieHardDisk</span> <span class="keyword">implements</span> <span class="title class_">HardDisk</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">save</span><span class="params">(String data)</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;使用希捷硬盘存储数据&quot;</span> + data);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">get</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;使用希捷希捷硬盘取数据&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;数据&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><strong>Intel 处理器（IntelCpu）：</strong></p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">IntelCpu</span> <span class="keyword">implements</span> <span class="title class_">Cpu</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;使用Intel处理器&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><strong>金士顿内存条（KingstonMemory）：</strong></p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">KingstonMemory</span> <span class="keyword">implements</span> <span class="title class_">Memory</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">save</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;使用金士顿作为内存条&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><strong>电脑（Computer）：</strong></p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Computer</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> XiJieHardDisk hardDisk;</span><br><span class="line">    <span class="keyword">private</span> IntelCpu cpu;</span><br><span class="line">    <span class="keyword">private</span> KingstonMemory memory;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> IntelCpu <span class="title function_">getCpu</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> cpu;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setCpu</span><span class="params">(IntelCpu cpu)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.cpu = cpu;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> KingstonMemory <span class="title function_">getMemory</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> memory;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setMemory</span><span class="params">(KingstonMemory memory)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.memory = memory;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> XiJieHardDisk <span class="title function_">getHardDisk</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> hardDisk;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setHardDisk</span><span class="params">(XiJieHardDisk hardDisk)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.hardDisk = hardDisk;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;计算机工作&quot;</span>);</span><br><span class="line">        cpu.run();</span><br><span class="line">        memory.save();</span><br><span class="line">        <span class="type">String</span> <span class="variable">data</span> <span class="operator">=</span> hardDisk.get();</span><br><span class="line">        System.out.println(<span class="string">&quot;从硬盘中获取的数据为：&quot;</span> + data);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><strong>测试类（TestComputer）：</strong></p>
<p>测试类用来组装电脑。</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TestComputer</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">Computer</span> <span class="variable">computer</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Computer</span>();</span><br><span class="line">        computer.setHardDisk(<span class="keyword">new</span> <span class="title class_">XiJieHardDisk</span>());</span><br><span class="line">        computer.setCpu(<span class="keyword">new</span> <span class="title class_">IntelCpu</span>());</span><br><span class="line">        computer.setMemory(<span class="keyword">new</span> <span class="title class_">KingstonMemory</span>());</span><br><span class="line"></span><br><span class="line">        computer.run();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>上面代码可以看到已经组装了一台电脑，但是似乎组装的电脑的 cpu 只能是 Intel 的，内存条只能是金士顿的，硬盘只能是希捷的，这对用户肯定是不友好的，用户有了机箱肯定是想按照自己的喜好，选择自己喜欢的配件。</p>
<p>根据依赖倒转原则进行改进：</p>
<p>代码我们只需要修改 Computer 类，让 Computer 类依赖抽象（各个配件的接口），而不是依赖于各个组件具体的实现类。</p>
<p><strong>类图如下：</strong><br>
<img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420225916824.png"
                      alt="在这里插入图片描述"
                ></p>
<p><strong>电脑（Computer）：</strong></p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Computer</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> HardDisk hardDisk;</span><br><span class="line">    <span class="keyword">private</span> Cpu cpu;</span><br><span class="line">    <span class="keyword">private</span> Memory memory;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> HardDisk <span class="title function_">getHardDisk</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> hardDisk;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setHardDisk</span><span class="params">(HardDisk hardDisk)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.hardDisk = hardDisk;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Cpu <span class="title function_">getCpu</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> cpu;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setCpu</span><span class="params">(Cpu cpu)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.cpu = cpu;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Memory <span class="title function_">getMemory</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> memory;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setMemory</span><span class="params">(Memory memory)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.memory = memory;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;计算机工作&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>面向对象的开发很好的解决了这个问题，一般情况下抽象的变化概率很小，让用户程序依赖于抽象，实现的细节也依赖于抽象。即使实现细节不断变动，只要抽象不变，客户程序就不需要变化。这大大降低了客户程序与实现细节的耦合度。</p>
<h2 id="34-接口隔离原则"><a class="markdownIt-Anchor" href="#34-接口隔离原则">#</a> 3.4 接口隔离原则</h2>
<p>客户端不应该被迫依赖于它不使用的方法；一个类对另一个类的依赖应该建立在最小的接口上。</p>
<p><strong>实现一个接口时如果有自己用不到的方法是违背原则的，可以将接口的拆分成多个接口，实现类只需要实现自己所需要的接口即可</strong></p>
<p>下面看一个例子来理解接口隔离原则</p>
<p>【例】安全门案例</p>
<p>我们需要创建一个 <code>黑马</code> 品牌的安全门，该安全门具有防火、防水、防盗的功能。可以将防火，防水，防盗功能提取成一个接口，形成一套规范。类图如下：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420225304649.png"
                      alt="在这里插入图片描述"
                ></p>
<p>上面的设计我们发现了它存在的问题，黑马品牌的安全门具有防盗，防水，防火的功能。现在如果我们还需要再创建一个传智品牌的安全门，而该安全门只具有防盗、防水功能呢？很显然如果实现 SafetyDoor 接口就违背了接口隔离原则，那么我们如何进行修改呢？看如下类图：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420225241132.png"
                      alt="在这里插入图片描述"
                ></p>
<p>代码如下：</p>
<p><strong>AntiTheft（接口）：</strong></p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">AntiTheft</span> &#123;</span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">antiTheft</span><span class="params">()</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><strong>Fireproof（接口）：</strong></p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">Fireproof</span> &#123;</span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">fireproof</span><span class="params">()</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><strong>Waterproof（接口）：</strong></p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">Waterproof</span> &#123;</span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">waterproof</span><span class="params">()</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><strong>HeiMaSafetyDoor（类）：</strong></p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">HeiMaSafetyDoor</span> <span class="keyword">implements</span> <span class="title class_">AntiTheft</span>,Fireproof,Waterproof &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">antiTheft</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;防盗&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">fireproof</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;防火&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">waterproof</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;防水&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><strong>ItcastSafetyDoor（类）：</strong></p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ItcastSafetyDoor</span> <span class="keyword">implements</span> <span class="title class_">AntiTheft</span>,Fireproof &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">antiTheft</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;防盗&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">fireproof</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;防火&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<h2 id="35-迪米特法则"><a class="markdownIt-Anchor" href="#35-迪米特法则">#</a> 3.5 迪米特法则</h2>
<p>迪米特法则又叫最少知识原则。</p>
<p><strong>使用中介降低调用类和方法类的耦合度</strong></p>
<p>只和你的直接朋友交谈，不跟 “陌生人” 说话（Talk only to your immediate friends and not to strangers）。</p>
<p>其含义是：如果两个软件实体无须直接通信，那么就不应当发生直接的相互调用，可以通过第三方转发该调用。其目的是降低类之间的耦合度，提高模块的相对独立性。</p>
<p>迪米特法则中的 “朋友” 是指：当前对象本身、当前对象的成员对象、当前对象所创建的对象、当前对象的方法参数等，这些对象同当前对象存在关联、聚合或组合关系，可以直接访问这些对象的方法。</p>
<p>下面看一个例子来理解迪米特法则</p>
<p>【例】明星与经纪人的关系实例</p>
<p>明星由于全身心投入艺术，所以许多日常事务由经纪人负责处理，如和粉丝的见面会，和媒体公司的业务洽淡等。这里的经纪人是明星的朋友，而粉丝和媒体公司是陌生人，所以适合使用迪米特法则。</p>
<p>类图如下：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/202104202259471.png"
                      alt="在这里插入图片描述"
                ></p>
<p>代码如下：</p>
<p><strong>明星类（Star）</strong></p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Star</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Star</span><span class="params">(String name)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.name=name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getName</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> name;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><strong>粉丝类（Fans）</strong></p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Fans</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Fans</span><span class="params">(String name)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.name=name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getName</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> name;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><strong>媒体公司类（Company）</strong></p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Company</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Company</span><span class="params">(String name)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.name=name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getName</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> name;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><strong>经纪人类（Agent）</strong></p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Agent</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> Star star;</span><br><span class="line">    <span class="keyword">private</span> Fans fans;</span><br><span class="line">    <span class="keyword">private</span> Company company;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setStar</span><span class="params">(Star star)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.star = star;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setFans</span><span class="params">(Fans fans)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.fans = fans;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setCompany</span><span class="params">(Company company)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.company = company;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">meeting</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(fans.getName() + <span class="string">&quot;与明星&quot;</span> + star.getName() + <span class="string">&quot;见面了。&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">business</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(company.getName() + <span class="string">&quot;与明星&quot;</span> + star.getName() + <span class="string">&quot;洽淡业务。&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<h2 id="36-合成复用原则"><a class="markdownIt-Anchor" href="#36-合成复用原则">#</a> 3.6 合成复用原则</h2>
<p>合成复用原则是指：<strong>尽量先使用组合或者聚合等关联关系来实现，其次才考虑使用继承关系来实现。</strong></p>
<p>通常类的复用分为继承复用和合成复用两种。</p>
<p>继承复用虽然有简单和易实现的优点，但它也存在以下缺点：</p>
<ol>
<li>继承复用破坏了类的封装性。因为继承会将父类的实现细节暴露给子类，父类对子类是透明的，所以这种复用又称为 “白箱” 复用。</li>
<li>子类与父类的耦合度高。父类的实现的任何改变都会导致子类的实现发生变化，这不利于类的扩展与维护。</li>
<li>它限制了复用的灵活性。从父类继承而来的实现是静态的，在编译时已经定义，所以在运行时不可能发生变化。</li>
</ol>
<p>采用组合或聚合复用时，可以将已有对象纳入新对象中，使之成为新对象的一部分，新对象可以调用已有对象的功能，它有以下优点：</p>
<ol>
<li>它维持了类的封装性。因为成分对象的内部细节是新对象看不见的，所以这种复用又称为 “黑箱” 复用。</li>
<li>对象间的耦合度低。可以在类的成员位置声明抽象。</li>
<li>复用的灵活性高。这种复用可以在运行时动态进行，新对象可以动态地引用与成分对象类型相同的对象。</li>
</ol>
<p>下面看一个例子来理解合成复用原则</p>
<p>【例】汽车分类管理程序</p>
<p>汽车按 “动力源” 划分可分为汽油汽车、电动汽车等；按 “颜色” 划分可分为白色汽车、黑色汽车和红色汽车等。如果同时考虑这两种分类，其组合就很多。类图如下：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420230021873.png"
                      alt="在这里插入图片描述"
                ></p>
<p>从上面类图我们可以看到使用继承复用产生了很多子类，如果现在又有新的动力源或者新的颜色的话，就需要再定义新的类。我们试着将继承复用改为聚合复用看一下。</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420230052402.png"
                      alt="在这里插入图片描述"
                ></p>
<h1 id="4创建型模式"><a class="markdownIt-Anchor" href="#4创建型模式">#</a> 4，创建型模式</h1>
<p>创建型模式的主要关注点是 “怎样创建对象？”，它的主要特点是 “将对象的创建与使用分离”。</p>
<p>这样可以降低系统的耦合度，使用者不需要关注对象的创建细节。</p>
<p>创建型模式分为：</p>
<ul>
<li>单例模式</li>
<li>工厂方法模式</li>
<li>抽象工程模式</li>
<li>原型模式</li>
<li>建造者模式</li>
</ul>
<h2 id="41-单例设计模式"><a class="markdownIt-Anchor" href="#41-单例设计模式">#</a> 4.1 单例设计模式</h2>
<p>单例模式（Singleton Pattern）是 Java 中最简单的设计模式之一。这种类型的设计模式属于创建型模式，它提供了一种创建对象的最佳方式。</p>
<p>这种模式涉及到一个单一的类，该类负责创建自己的对象，同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式，可以直接访问，不需要实例化该类的对象。</p>
<h3 id="411-单例模式的结构"><a class="markdownIt-Anchor" href="#411-单例模式的结构">#</a> 4.1.1 单例模式的结构</h3>
<p>单例模式的主要有以下角色：</p>
<ul>
<li>单例类。只能创建一个实例的类</li>
<li>访问类。使用单例类</li>
</ul>
<h3 id="412-单例模式的实现"><a class="markdownIt-Anchor" href="#412-单例模式的实现">#</a> 4.1.2 单例模式的实现</h3>
<blockquote>
<p>单例设计模式分类两种：</p>
<p>饿汉式：类加载就会导致该单实例对象被创建</p>
<p>懒汉式：类加载不会导致该单实例对象被创建，而是首次使用该对象时才会创建</p>
</blockquote>
<ol>
<li>
<p>饿汉式 - 方式 1（静态变量方式）</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 饿汉式</span></span><br><span class="line"><span class="comment"> *      静态变量创建类的对象</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Singleton</span> &#123;</span><br><span class="line">    <span class="comment">//私有构造方法</span></span><br><span class="line">    <span class="keyword">private</span> <span class="title function_">Singleton</span><span class="params">()</span> &#123;&#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//在成员位置创建该类的对象</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="type">Singleton</span> <span class="variable">instance</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Singleton</span>();</span><br><span class="line"></span><br><span class="line">    <span class="comment">//对外提供静态方法获取该对象</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> Singleton <span class="title function_">getInstance</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> instance;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><font color='red'>说明：</font></p>
<p>该方式在成员位置声明 Singleton 类型的静态变量，并创建 Singleton 类的对象 instance。instance 对象是随着类的加载而创建的。如果该对象足够大的话，而一直没有使用就会造成内存的浪费。</p>
</li>
<li>
<p>饿汉式 - 方式 2（静态代码块方式）</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 恶汉式</span></span><br><span class="line"><span class="comment"> *      在静态代码块中创建该类对象</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Singleton</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//私有构造方法</span></span><br><span class="line">    <span class="keyword">private</span> <span class="title function_">Singleton</span><span class="params">()</span> &#123;&#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//在成员位置创建该类的对象</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Singleton instance;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> &#123;</span><br><span class="line">        instance = <span class="keyword">new</span> <span class="title class_">Singleton</span>();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//对外提供静态方法获取该对象</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> Singleton <span class="title function_">getInstance</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> instance;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><font color='red'>说明：</font></p>
<p>该方式在成员位置声明 Singleton 类型的静态变量，而对象的创建是在静态代码块中，也是对着类的加载而创建。所以和饿汉式的方式 1 基本上一样，当然该方式也存在内存浪费问题。</p>
</li>
<li>
<p>懒汉式 - 方式 1（线程不安全）</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 懒汉式</span></span><br><span class="line"><span class="comment"> *  线程不安全</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Singleton</span> &#123;</span><br><span class="line">    <span class="comment">//私有构造方法</span></span><br><span class="line">    <span class="keyword">private</span> <span class="title function_">Singleton</span><span class="params">()</span> &#123;&#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//在成员位置创建该类的对象</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Singleton instance;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//对外提供静态方法获取该对象</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> Singleton <span class="title function_">getInstance</span><span class="params">()</span> &#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span>(instance == <span class="literal">null</span>) &#123;</span><br><span class="line">            instance = <span class="keyword">new</span> <span class="title class_">Singleton</span>();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> instance;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><font color='red'>说明：</font></p>
<p>从上面代码我们可以看出该方式在成员位置声明 Singleton 类型的静态变量，并没有进行对象的赋值操作，那么什么时候赋值的呢？当调用 getInstance () 方法获取 Singleton 类的对象的时候才创建 Singleton 类的对象，这样就实现了懒加载的效果。但是，如果是多线程环境，会出现线程安全问题。</p>
</li>
<li>
<p>懒汉式 - 方式 2（线程安全）</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 懒汉式</span></span><br><span class="line"><span class="comment"> *  线程安全</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Singleton</span> &#123;</span><br><span class="line">    <span class="comment">//私有构造方法</span></span><br><span class="line">    <span class="keyword">private</span> <span class="title function_">Singleton</span><span class="params">()</span> &#123;&#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//在成员位置创建该类的对象</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Singleton instance;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//对外提供静态方法获取该对象</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">synchronized</span> Singleton <span class="title function_">getInstance</span><span class="params">()</span> &#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span>(instance == <span class="literal">null</span>) &#123;</span><br><span class="line">            instance = <span class="keyword">new</span> <span class="title class_">Singleton</span>();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> instance;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><font color='red'>说明：</font></p>
<p>该方式也实现了懒加载效果，同时又解决了线程安全问题。但是在 getInstance () 方法上添加了 synchronized 关键字，导致该方法的执行效果特别低。从上面代码我们可以看出，其实就是在初始化 instance 的时候才会出现线程安全问题，一旦初始化完成就不存在了。</p>
</li>
<li>
<p>懒汉式 - 方式 3（双重检查锁）</p>
<p>再来讨论一下懒汉模式中加锁的问题，对于  <code>getInstance()</code>  方法来说，绝大部分的操作都是读操作，读操作是线程安全的，所以我们没必让每个线程必须持有锁才能调用该方法，我们需要调整加锁的时机。由此也产生了一种新的实现模式：双重检查锁模式</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 双重检查方式</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Singleton</span> &#123; </span><br><span class="line"></span><br><span class="line">    <span class="comment">//私有构造方法</span></span><br><span class="line">    <span class="keyword">private</span> <span class="title function_">Singleton</span><span class="params">()</span> &#123;&#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Singleton instance;</span><br><span class="line"></span><br><span class="line">   <span class="comment">//对外提供静态方法获取该对象</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> Singleton <span class="title function_">getInstance</span><span class="params">()</span> &#123;</span><br><span class="line">		<span class="comment">//第一次判断，如果instance不为null，不进入抢锁阶段，直接返回实例</span></span><br><span class="line">        <span class="keyword">if</span>(instance == <span class="literal">null</span>) &#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (Singleton.class) &#123;</span><br><span class="line">                <span class="comment">//抢到锁之后再次判断是否为null</span></span><br><span class="line">                <span class="keyword">if</span>(instance == <span class="literal">null</span>) &#123;</span><br><span class="line">                    instance = <span class="keyword">new</span> <span class="title class_">Singleton</span>();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> instance;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>双重检查锁模式是一种非常好的单例实现模式，解决了单例、性能、线程安全问题，上面的双重检测锁模式看上去完美无缺，其实是存在问题，在多线程的情况下，可能会出现空指针问题，出现问题的原因是 JVM 在实例化对象的时候会进行优化和指令重排序操作。</p>
<p>要解决双重检查锁模式带来空指针异常的问题，只需要使用  <code>volatile</code>  关键字， <code>volatile</code>  关键字可以保证可见性和有序性。</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 双重检查方式</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Singleton</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//私有构造方法</span></span><br><span class="line">    <span class="keyword">private</span> <span class="title function_">Singleton</span><span class="params">()</span> &#123;&#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">volatile</span> Singleton instance;</span><br><span class="line"></span><br><span class="line">   <span class="comment">//对外提供静态方法获取该对象</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> Singleton <span class="title function_">getInstance</span><span class="params">()</span> &#123;</span><br><span class="line">		<span class="comment">//第一次判断，如果instance不为null，不进入抢锁阶段，直接返回实际</span></span><br><span class="line">        <span class="keyword">if</span>(instance == <span class="literal">null</span>) &#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (Singleton.class) &#123;</span><br><span class="line">                <span class="comment">//抢到锁之后再次判断是否为空</span></span><br><span class="line">                <span class="keyword">if</span>(instance == <span class="literal">null</span>) &#123;</span><br><span class="line">                    instance = <span class="keyword">new</span> <span class="title class_">Singleton</span>();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> instance;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><font color="red">小结：</font></p>
<p>添加  <code>volatile</code>  关键字之后的双重检查锁模式是一种比较好的单例实现模式，能够保证在多线程的情况下线程安全也不会有性能问题。</p>
</li>
<li>
<p>懒汉式 - 方式 4（静态内部类方式）</p>
<p>静态内部类单例模式中实例由内部类创建，由于 JVM 在加载外部类的过程中，是不会加载静态内部类的，只有内部类的属性 / 方法被调用时才会被加载，并初始化其静态属性。静态属性由于被  <code>static</code>  修饰，保证只被实例化一次，并且严格保证实例化顺序。</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 静态内部类方式</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Singleton</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//私有构造方法</span></span><br><span class="line">    <span class="keyword">private</span> <span class="title function_">Singleton</span><span class="params">()</span> &#123;&#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">class</span> <span class="title class_">SingletonHolder</span> &#123;</span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">Singleton</span> <span class="variable">INSTANCE</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Singleton</span>();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//对外提供静态方法获取该对象</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> Singleton <span class="title function_">getInstance</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> SingletonHolder.INSTANCE;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><font color='red'>说明：</font></p>
<p>第一次加载 Singleton 类时不会去初始化 INSTANCE，只有第一次调用 getInstance，虚拟机加载 SingletonHolder</p>
<p>并初始化 INSTANCE，这样不仅能确保线程安全，也能保证 Singleton 类的唯一性。</p>
<p><font color="red">小结：</font></p>
<p>静态内部类单例模式是一种优秀的单例模式，是开源项目中比较常用的一种单例模式。在没有加任何锁的情况下，保证了多线程下的安全，并且没有任何性能影响和空间的浪费。</p>
</li>
<li>
<p>枚举方式</p>
<p>枚举类实现单例模式是极力推荐的单例实现模式，因为枚举类型是线程安全的，并且只会装载一次，设计者充分的利用了枚举的这个特性来实现单例模式，枚举的写法非常简单，而且枚举类型是所用单例实现中唯一一种不会被破坏的单例实现模式。</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 枚举方式</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">enum</span> <span class="title class_">Singleton</span> &#123;</span><br><span class="line">    INSTANCE;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><font color='red'>说明：</font></p>
<p>枚举方式属于恶汉式方式。</p>
</li>
</ol>
<h3 id="413-存在的问题"><a class="markdownIt-Anchor" href="#413-存在的问题">#</a> 4.1.3 存在的问题</h3>
<h4 id="4131-问题演示"><a class="markdownIt-Anchor" href="#4131-问题演示">#</a> 4.1.3.1 问题演示</h4>
<p>破坏单例模式：</p>
<p>使上面定义的单例类（Singleton）可以创建多个对象，枚举方式除外。有两种方式，分别是序列化和反射。</p>
<ul>
<li>
<p>序列化反序列化</p>
<p><strong>Singleton 类：</strong></p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Singleton</span> <span class="keyword">implements</span> <span class="title class_">Serializable</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//私有构造方法</span></span><br><span class="line">    <span class="keyword">private</span> <span class="title function_">Singleton</span><span class="params">()</span> &#123;&#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">class</span> <span class="title class_">SingletonHolder</span> &#123;</span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">Singleton</span> <span class="variable">INSTANCE</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Singleton</span>();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//对外提供静态方法获取该对象</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> Singleton <span class="title function_">getInstance</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> SingletonHolder.INSTANCE;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><strong>Test 类：</strong></p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Test</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="comment">//往文件中写对象</span></span><br><span class="line">        <span class="comment">//writeObject2File();</span></span><br><span class="line">        <span class="comment">//从文件中读取对象</span></span><br><span class="line">        <span class="type">Singleton</span> <span class="variable">s1</span> <span class="operator">=</span> readObjectFromFile();</span><br><span class="line">        <span class="type">Singleton</span> <span class="variable">s2</span> <span class="operator">=</span> readObjectFromFile();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//判断两个反序列化后的对象是否是同一个对象</span></span><br><span class="line">        System.out.println(s1 == s2);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Singleton <span class="title function_">readObjectFromFile</span><span class="params">()</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="comment">//创建对象输入流对象</span></span><br><span class="line">        <span class="type">ObjectInputStream</span> <span class="variable">ois</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ObjectInputStream</span>(<span class="keyword">new</span> <span class="title class_">FileInputStream</span>(<span class="string">&quot;C:\\Users\\Think\\Desktop\\a.txt&quot;</span>));</span><br><span class="line">        <span class="comment">//第一个读取Singleton对象</span></span><br><span class="line">        <span class="type">Singleton</span> <span class="variable">instance</span> <span class="operator">=</span> (Singleton) ois.readObject();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> instance;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">writeObject2File</span><span class="params">()</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="comment">//获取Singleton类的对象</span></span><br><span class="line">        <span class="type">Singleton</span> <span class="variable">instance</span> <span class="operator">=</span> Singleton.getInstance();</span><br><span class="line">        <span class="comment">//创建对象输出流</span></span><br><span class="line">        <span class="type">ObjectOutputStream</span> <span class="variable">oos</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ObjectOutputStream</span>(<span class="keyword">new</span> <span class="title class_">FileOutputStream</span>(<span class="string">&quot;C:\\Users\\Think\\Desktop\\a.txt&quot;</span>));</span><br><span class="line">        <span class="comment">//将instance对象写出到文件中</span></span><br><span class="line">        oos.writeObject(instance);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<blockquote>
<p>上面代码运行结果是 <code>false</code> ，表明序列化和反序列化已经破坏了单例设计模式。</p>
</blockquote>
</li>
<li>
<p>反射</p>
<p><strong>Singleton 类：</strong></p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Singleton</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//私有构造方法</span></span><br><span class="line">    <span class="keyword">private</span> <span class="title function_">Singleton</span><span class="params">()</span> &#123;&#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">volatile</span> Singleton instance;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//对外提供静态方法获取该对象</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> Singleton <span class="title function_">getInstance</span><span class="params">()</span> &#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span>(instance != <span class="literal">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> instance;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">synchronized</span> (Singleton.class) &#123;</span><br><span class="line">            <span class="keyword">if</span>(instance != <span class="literal">null</span>) &#123;</span><br><span class="line">                <span class="keyword">return</span> instance;</span><br><span class="line">            &#125;</span><br><span class="line">            instance = <span class="keyword">new</span> <span class="title class_">Singleton</span>();</span><br><span class="line">            <span class="keyword">return</span> instance;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><strong>Test 类：</strong></p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Test</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="comment">//获取Singleton类的字节码对象</span></span><br><span class="line">        <span class="type">Class</span> <span class="variable">clazz</span> <span class="operator">=</span> Singleton.class;</span><br><span class="line">        <span class="comment">//获取Singleton类的私有无参构造方法对象</span></span><br><span class="line">        <span class="type">Constructor</span> <span class="variable">constructor</span> <span class="operator">=</span> clazz.getDeclaredConstructor();</span><br><span class="line">        <span class="comment">//取消访问检查</span></span><br><span class="line">        constructor.setAccessible(<span class="literal">true</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建Singleton类的对象s1</span></span><br><span class="line">        <span class="type">Singleton</span> <span class="variable">s1</span> <span class="operator">=</span> (Singleton) constructor.newInstance();</span><br><span class="line">        <span class="comment">//创建Singleton类的对象s2</span></span><br><span class="line">        <span class="type">Singleton</span> <span class="variable">s2</span> <span class="operator">=</span> (Singleton) constructor.newInstance();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//判断通过反射创建的两个Singleton对象是否是同一个对象</span></span><br><span class="line">        System.out.println(s1 == s2);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<blockquote>
<p>上面代码运行结果是 <code>false</code> ，表明序列化和反序列化已经破坏了单例设计模式</p>
</blockquote>
</li>
</ul>
<blockquote>
<p><font color="red">注意：</font>枚举方式不会出现这两个问题。</p>
</blockquote>
<h4 id="4132-问题的解决"><a class="markdownIt-Anchor" href="#4132-问题的解决">#</a> 4.1.3.2 问题的解决</h4>
<ul>
<li>
<p>序列化、反序列方式破坏单例模式的解决方法</p>
<p>在 Singleton 类中添加 <code>readResolve()</code>  方法，在反序列化时被反射调用，如果定义了这个方法，就返回这个方法的值，如果没有定义，则返回新 new 出来的对象。</p>
<p><strong>Singleton 类：</strong></p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Singleton</span> <span class="keyword">implements</span> <span class="title class_">Serializable</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//私有构造方法</span></span><br><span class="line">    <span class="keyword">private</span> <span class="title function_">Singleton</span><span class="params">()</span> &#123;&#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">class</span> <span class="title class_">SingletonHolder</span> &#123;</span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">Singleton</span> <span class="variable">INSTANCE</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Singleton</span>();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//对外提供静态方法获取该对象</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> Singleton <span class="title function_">getInstance</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> SingletonHolder.INSTANCE;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 下面是为了解决序列化反序列化破解单例模式</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> Object <span class="title function_">readResolve</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> SingletonHolder.INSTANCE;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><strong>源码解析：</strong></p>
<p>ObjectInputStream 类</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> Object <span class="title function_">readObject</span><span class="params">()</span> <span class="keyword">throws</span> IOException, ClassNotFoundException&#123;</span><br><span class="line">    ...</span><br><span class="line">    <span class="comment">// if nested read, passHandle contains handle of enclosing object</span></span><br><span class="line">    <span class="type">int</span> <span class="variable">outerHandle</span> <span class="operator">=</span> passHandle;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="type">Object</span> <span class="variable">obj</span> <span class="operator">=</span> readObject0(<span class="literal">false</span>);<span class="comment">//重点查看readObject0方法</span></span><br><span class="line">    .....</span><br><span class="line">&#125;</span><br><span class="line">    </span><br><span class="line"><span class="keyword">private</span> Object <span class="title function_">readObject0</span><span class="params">(<span class="type">boolean</span> unshared)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">	...</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">		<span class="keyword">switch</span> (tc) &#123;</span><br><span class="line">			...</span><br><span class="line">			<span class="keyword">case</span> TC_OBJECT:</span><br><span class="line">				<span class="keyword">return</span> checkResolve(readOrdinaryObject(unshared));<span class="comment">//重点查看readOrdinaryObject方法</span></span><br><span class="line">			...</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        depth--;</span><br><span class="line">        bin.setBlockDataMode(oldMode);</span><br><span class="line">    &#125;    </span><br><span class="line">&#125;</span><br><span class="line">    </span><br><span class="line"><span class="keyword">private</span> Object <span class="title function_">readOrdinaryObject</span><span class="params">(<span class="type">boolean</span> unshared)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">	...</span><br><span class="line">	<span class="comment">//isInstantiable 返回true，执行 desc.newInstance()，通过反射创建新的单例类，</span></span><br><span class="line">    obj = desc.isInstantiable() ? desc.newInstance() : <span class="literal">null</span>; </span><br><span class="line">    ...</span><br><span class="line">    <span class="comment">// 在Singleton类中添加 readResolve 方法后 desc.hasReadResolveMethod() 方法执行结果为true</span></span><br><span class="line">    <span class="keyword">if</span> (obj != <span class="literal">null</span> &amp;&amp; handles.lookupException(passHandle) == <span class="literal">null</span> &amp;&amp; desc.hasReadResolveMethod()) &#123;</span><br><span class="line">    	<span class="comment">// 通过反射调用 Singleton 类中的 readResolve 方法，将返回值赋值给rep变量</span></span><br><span class="line">    	<span class="comment">// 这样多次调用ObjectInputStream类中的readObject方法，继而就会调用我们定义的readResolve方法，所以返回的是同一个对象。</span></span><br><span class="line">    	<span class="type">Object</span> <span class="variable">rep</span> <span class="operator">=</span> desc.invokeReadResolve(obj);</span><br><span class="line">     	...</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> obj;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
</li>
<li>
<p>反射方式破解单例的解决方法</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Singleton</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//私有构造方法</span></span><br><span class="line">    <span class="keyword">private</span> <span class="title function_">Singleton</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">           反射破解单例模式需要添加的代码</span></span><br><span class="line"><span class="comment">        */</span></span><br><span class="line">        <span class="keyword">if</span>(instance != <span class="literal">null</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">RuntimeException</span>();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">volatile</span> Singleton instance;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//对外提供静态方法获取该对象</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> Singleton <span class="title function_">getInstance</span><span class="params">()</span> &#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span>(instance != <span class="literal">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> instance;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">synchronized</span> (Singleton.class) &#123;</span><br><span class="line">            <span class="keyword">if</span>(instance != <span class="literal">null</span>) &#123;</span><br><span class="line">                <span class="keyword">return</span> instance;</span><br><span class="line">            &#125;</span><br><span class="line">            instance = <span class="keyword">new</span> <span class="title class_">Singleton</span>();</span><br><span class="line">            <span class="keyword">return</span> instance;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><font color="red">说明:</font></p>
<p>这种方式比较好理解。当通过反射方式调用构造方法进行创建创建时，直接抛异常。不运行此中操作。</p>
</li>
</ul>
<h3 id="414-jdk源码解析-runtime类"><a class="markdownIt-Anchor" href="#414-jdk源码解析-runtime类">#</a> 4.1.4 JDK 源码解析 - Runtime 类</h3>
<p>Runtime 类就是使用的单例设计模式。</p>
<ol>
<li>
<p>通过源代码查看使用的是哪儿种单例模式</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Runtime</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="type">Runtime</span> <span class="variable">currentRuntime</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Runtime</span>();</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Returns the runtime object associated with the current Java application.</span></span><br><span class="line"><span class="comment">     * Most of the methods of class &lt;code&gt;Runtime&lt;/code&gt; are instance</span></span><br><span class="line"><span class="comment">     * methods and must be invoked with respect to the current runtime object.</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span>  the &lt;code&gt;Runtime&lt;/code&gt; object associated with the current</span></span><br><span class="line"><span class="comment">     *          Java application.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> Runtime <span class="title function_">getRuntime</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> currentRuntime;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/** Don&#x27;t let anyone else instantiate this class */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="title function_">Runtime</span><span class="params">()</span> &#123;&#125;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>从上面源代码中可以看出 Runtime 类使用的是恶汉式（静态属性）方式来实现单例模式的。</p>
</li>
<li>
<p>使用 Runtime 类中的方法</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">RuntimeDemo</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">        <span class="comment">//获取Runtime类对象</span></span><br><span class="line">        <span class="type">Runtime</span> <span class="variable">runtime</span> <span class="operator">=</span> Runtime.getRuntime();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//返回 Java 虚拟机中的内存总量。</span></span><br><span class="line">        System.out.println(runtime.totalMemory());</span><br><span class="line">        <span class="comment">//返回 Java 虚拟机试图使用的最大内存量。</span></span><br><span class="line">        System.out.println(runtime.maxMemory());</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建一个新的进程执行指定的字符串命令，返回进程对象</span></span><br><span class="line">        <span class="type">Process</span> <span class="variable">process</span> <span class="operator">=</span> runtime.exec(<span class="string">&quot;ipconfig&quot;</span>);</span><br><span class="line">        <span class="comment">//获取命令执行后的结果，通过输入流获取</span></span><br><span class="line">        <span class="type">InputStream</span> <span class="variable">inputStream</span> <span class="operator">=</span> process.getInputStream();</span><br><span class="line">        <span class="type">byte</span>[] arr = <span class="keyword">new</span> <span class="title class_">byte</span>[<span class="number">1024</span> * <span class="number">1024</span>* <span class="number">100</span>];</span><br><span class="line">        <span class="type">int</span> <span class="variable">b</span> <span class="operator">=</span> inputStream.read(arr);</span><br><span class="line">        System.out.println(<span class="keyword">new</span> <span class="title class_">String</span>(arr,<span class="number">0</span>,b,<span class="string">&quot;gbk&quot;</span>));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
</li>
</ol>
<h2 id="42-工厂模式"><a class="markdownIt-Anchor" href="#42-工厂模式">#</a> 4.2 工厂模式</h2>
<h3 id="421-概述"><a class="markdownIt-Anchor" href="#421-概述">#</a> 4.2.1 概述</h3>
<p>需求：设计一个咖啡店点餐系统。</p>
<p>设计一个咖啡类（Coffee），并定义其两个子类（美式咖啡【AmericanCoffee】和拿铁咖啡【LatteCoffee】）；再设计一个咖啡店类（CoffeeStore），咖啡店具有点咖啡的功能。</p>
<p>具体类的设计如下：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420230134217.png"
                      alt="在这里插入图片描述"
                ></p>
<p>在 java 中，万物皆对象，这些对象都需要创建，如果创建的时候直接 new 该对象，就会对该对象耦合严重，假如我们要更换对象，所有 new 对象的地方都需要修改一遍，这显然违背了软件设计的开闭原则。如果我们使用工厂来生产对象，我们就只和工厂打交道就可以了，彻底和对象解耦，如果要更换对象，直接在工厂里更换该对象即可，达到了与对象解耦的目的；所以说，工厂模式最大的优点就是：<strong>解耦</strong>。</p>
<p>在本教程中会介绍三种工厂的使用</p>
<ul>
<li>简单工厂模式（不属于 GOF 的 23 种经典设计模式）</li>
<li>工厂方法模式</li>
<li>抽象工厂模式</li>
</ul>
<h3 id="422-简单工厂模式"><a class="markdownIt-Anchor" href="#422-简单工厂模式">#</a> 4.2.2 简单工厂模式</h3>
<p>简单工厂不是一种设计模式，反而比较像是一种编程习惯。</p>
<h4 id="4221-结构"><a class="markdownIt-Anchor" href="#4221-结构">#</a> 4.2.2.1 结构</h4>
<p>简单工厂包含如下角色：</p>
<ul>
<li>抽象产品 ：定义了产品的规范，描述了产品的主要特性和功能。</li>
<li>具体产品 ：实现或者继承抽象产品的子类</li>
<li>具体工厂 ：提供了创建产品的方法，调用者通过该方法来获取产品。</li>
</ul>
<h4 id="4222-实现"><a class="markdownIt-Anchor" href="#4222-实现">#</a> 4.2.2.2 实现</h4>
<p>现在使用简单工厂对上面案例进行改进，类图如下：<br>
<img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420230250942.png"
                      alt="在这里插入图片描述"
                ></p>
<p>工厂类代码如下：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">SimpleCoffeeFactory</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Coffee <span class="title function_">createCoffee</span><span class="params">(String type)</span> &#123;</span><br><span class="line">        <span class="type">Coffee</span> <span class="variable">coffee</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">        <span class="keyword">if</span>(<span class="string">&quot;americano&quot;</span>.equals(type)) &#123;</span><br><span class="line">            coffee = <span class="keyword">new</span> <span class="title class_">AmericanoCoffee</span>();</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span>(<span class="string">&quot;latte&quot;</span>.equals(type)) &#123;</span><br><span class="line">            coffee = <span class="keyword">new</span> <span class="title class_">LatteCoffee</span>();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> coffee;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>工厂（factory）处理创建对象的细节，一旦有了 SimpleCoffeeFactory，CoffeeStore 类中的 orderCoffee () 就变成此对象的客户，后期如果需要 Coffee 对象直接从工厂中获取即可。这样也就解除了和 Coffee 实现类的耦合，同时又产生了新的耦合，CoffeeStore 对象和 SimpleCoffeeFactory 工厂对象的耦合，工厂对象和商品对象的耦合。</p>
<p>后期如果再加新品种的咖啡，我们势必要需求修改 SimpleCoffeeFactory 的代码，违反了开闭原则。工厂类的客户端可能有很多，比如创建美团外卖等，这样只需要修改工厂类的代码，省去其他的修改操作。</p>
<h4 id="4224-优缺点"><a class="markdownIt-Anchor" href="#4224-优缺点">#</a> 4.2.2.4 优缺点</h4>
<p><strong>优点：</strong></p>
<p>封装了创建对象的过程，可以通过参数直接获取对象。把对象的创建和业务逻辑层分开，这样以后就避免了修改客户代码，如果要实现新产品直接修改工厂类，而不需要在原代码中修改，这样就降低了客户代码修改的可能性，更加容易扩展。</p>
<p><strong>缺点：</strong></p>
<p>增加新产品时还是需要修改工厂类的代码，违背了 “开闭原则”。</p>
<h4 id="4223-扩展"><a class="markdownIt-Anchor" href="#4223-扩展">#</a> 4.2.2.3 扩展</h4>
<p><strong>静态工厂</strong></p>
<p>在开发中也有一部分人将工厂类中的创建对象的功能定义为静态的，这个就是静态工厂模式，它也不是 23 种设计模式中的。代码如下：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">SimpleCoffeeFactory</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> Coffee <span class="title function_">createCoffee</span><span class="params">(String type)</span> &#123;</span><br><span class="line">        <span class="type">Coffee</span> <span class="variable">coffee</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">        <span class="keyword">if</span>(<span class="string">&quot;americano&quot;</span>.equals(type)) &#123;</span><br><span class="line">            coffee = <span class="keyword">new</span> <span class="title class_">AmericanoCoffee</span>();</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span>(<span class="string">&quot;latte&quot;</span>.equals(type)) &#123;</span><br><span class="line">            coffee = <span class="keyword">new</span> <span class="title class_">LatteCoffee</span>();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> coffe;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<h3 id="423-工厂方法模式"><a class="markdownIt-Anchor" href="#423-工厂方法模式">#</a> 4.2.3 工厂方法模式</h3>
<p>针对上例中的缺点，使用工厂方法模式就可以完美的解决，完全遵循开闭原则。</p>
<h4 id="4231-概念"><a class="markdownIt-Anchor" href="#4231-概念">#</a> 4.2.3.1 概念</h4>
<p>定义一个用于创建对象的接口，让子类决定实例化哪个产品类对象。工厂方法使一个产品类的实例化延迟到其工厂的子类。</p>
<h4 id="4232-结构"><a class="markdownIt-Anchor" href="#4232-结构">#</a> 4.2.3.2 结构</h4>
<p>工厂方法模式的主要角色：</p>
<ul>
<li>抽象工厂（Abstract Factory）：提供了创建产品的接口，调用者通过它访问具体工厂的工厂方法来创建产品。</li>
<li>具体工厂（ConcreteFactory）：主要是实现抽象工厂中的抽象方法，完成具体产品的创建。</li>
<li>抽象产品（Product）：定义了产品的规范，描述了产品的主要特性和功能。</li>
<li>具体产品（ConcreteProduct）：实现了抽象产品角色所定义的接口，由具体工厂来创建，它同具体工厂之间一一对应。</li>
</ul>
<h4 id="4233-实现"><a class="markdownIt-Anchor" href="#4233-实现">#</a> 4.2.3.3 实现</h4>
<p>使用工厂方法模式对上例进行改进，类图如下：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420230327522.png"
                      alt="在这里插入图片描述"
                ></p>
<p>代码如下：</p>
<p>抽象工厂：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">CoffeeFactory</span> &#123;</span><br><span class="line"></span><br><span class="line">    Coffee <span class="title function_">createCoffee</span><span class="params">()</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>具体工厂：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">LatteCoffeeFactory</span> <span class="keyword">implements</span> <span class="title class_">CoffeeFactory</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Coffee <span class="title function_">createCoffee</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">LatteCoffee</span>();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">AmericanCoffeeFactory</span> <span class="keyword">implements</span> <span class="title class_">CoffeeFactory</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Coffee <span class="title function_">createCoffee</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">AmericanCoffee</span>();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>咖啡店类：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">CoffeeStore</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> CoffeeFactory factory;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">CoffeeStore</span><span class="params">(CoffeeFactory factory)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.factory = factory;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Coffee <span class="title function_">orderCoffee</span><span class="params">(String type)</span> &#123;</span><br><span class="line">        <span class="type">Coffee</span> <span class="variable">coffee</span> <span class="operator">=</span> factory.createCoffee();</span><br><span class="line">        coffee.addMilk();</span><br><span class="line">        coffee.addsugar();</span><br><span class="line">        <span class="keyword">return</span> coffee;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>从以上的编写的代码可以看到，要增加产品类时也要相应地增加工厂类，不需要修改工厂类的代码了，这样就解决了简单工厂模式的缺点。</p>
<p>工厂方法模式是简单工厂模式的进一步抽象。由于使用了多态性，工厂方法模式保持了简单工厂模式的优点，而且克服了它的缺点。</p>
<h4 id="4234-优缺点"><a class="markdownIt-Anchor" href="#4234-优缺点">#</a> 4.2.3.4 优缺点</h4>
<p><strong>优点：</strong></p>
<ul>
<li>用户只需要知道具体工厂的名称就可得到所要的产品，无须知道产品的具体创建过程；</li>
<li>在系统增加新的产品时只需要添加具体产品类和对应的具体工厂类，无须对原工厂进行任何修改，满足开闭原则；</li>
</ul>
<p><strong>缺点：</strong></p>
<ul>
<li>每增加一个产品就要增加一个具体产品类和一个对应的具体工厂类，这增加了系统的复杂度。</li>
</ul>
<h3 id="424-抽象工厂模式"><a class="markdownIt-Anchor" href="#424-抽象工厂模式">#</a> 4.2.4 抽象工厂模式</h3>
<p>前面介绍的工厂方法模式中考虑的是一类产品的生产，如畜牧场只养动物、电视机厂只生产电视机、传智播客只培养计算机软件专业的学生等。</p>
<p>这些工厂只生产同种类产品，同种类产品称为同等级产品，也就是说：工厂方法模式只考虑生产同等级的产品，但是在现实生活中许多工厂是综合型的工厂，能生产多等级（种类） 的产品，如电器厂既生产电视机又生产洗衣机或空调，大学既有软件专业又有生物专业等。</p>
<p>本节要介绍的抽象工厂模式将考虑多等级产品的生产，将同一个具体工厂所生产的位于不同等级的一组产品称为一个产品族，下图所示横轴是产品等级，也就是同一类产品；纵轴是产品族，也就是同一品牌的产品，同一品牌的产品产自同一个工厂。</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420230400215.png"
                      alt="在这里插入图片描述"
                ></p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420230428784.png"
                      alt="在这里插入图片描述"
                ></p>
<h4 id="4241-概念"><a class="markdownIt-Anchor" href="#4241-概念">#</a> 4.2.4.1 概念</h4>
<p>是一种为访问类提供一个创建一组相关或相互依赖对象的接口，且访问类无须指定所要产品的具体类就能得到同族的不同等级的产品的模式结构。</p>
<p>抽象工厂模式是工厂方法模式的升级版本，工厂方法模式只生产一个等级的产品，而抽象工厂模式可生产多个等级的产品。</p>
<h4 id="4242-结构"><a class="markdownIt-Anchor" href="#4242-结构">#</a> 4.2.4.2 结构</h4>
<p>抽象工厂模式的主要角色如下：</p>
<ul>
<li>抽象工厂（Abstract Factory）：提供了创建产品的接口，它包含多个创建产品的方法，可以创建多个不同等级的产品。</li>
<li>具体工厂（Concrete Factory）：主要是实现抽象工厂中的多个抽象方法，完成具体产品的创建。</li>
<li>抽象产品（Product）：定义了产品的规范，描述了产品的主要特性和功能，抽象工厂模式有多个抽象产品。</li>
<li>具体产品（ConcreteProduct）：实现了抽象产品角色所定义的接口，由具体工厂来创建，它 同具体工厂之间是多对一的关系。</li>
</ul>
<h4 id="4242-实现"><a class="markdownIt-Anchor" href="#4242-实现">#</a> 4.2.4.2 实现</h4>
<p>现咖啡店业务发生改变，不仅要生产咖啡还要生产甜点，如提拉米苏、抹茶慕斯等，要是按照工厂方法模式，需要定义提拉米苏类、抹茶慕斯类、提拉米苏工厂、抹茶慕斯工厂、甜点工厂类，很容易发生类爆炸情况。其中拿铁咖啡、美式咖啡是一个产品等级，都是咖啡；提拉米苏、抹茶慕斯也是一个产品等级；拿铁咖啡和提拉米苏是同一产品族（也就是都属于意大利风味），美式咖啡和抹茶慕斯是同一产品族（也就是都属于美式风味）。所以这个案例可以使用抽象工厂模式实现。类图如下：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420230453918.png"
                      alt="在这里插入图片描述"
                ></p>
<p>代码如下：</p>
<p>抽象工厂：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">DessertFactory</span> &#123;</span><br><span class="line"></span><br><span class="line">    Coffee <span class="title function_">createCoffee</span><span class="params">()</span>;</span><br><span class="line"></span><br><span class="line">    Dessert <span class="title function_">createDessert</span><span class="params">()</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>具体工厂：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//美式甜点工厂</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">AmericanDessertFactory</span> <span class="keyword">implements</span> <span class="title class_">DessertFactory</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Coffee <span class="title function_">createCoffee</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">AmericanCoffee</span>();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Dessert <span class="title function_">createDessert</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">MatchaMousse</span>();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//意大利风味甜点工厂</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ItalyDessertFactory</span> <span class="keyword">implements</span> <span class="title class_">DessertFactory</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Coffee <span class="title function_">createCoffee</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">LatteCoffee</span>();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Dessert <span class="title function_">createDessert</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Tiramisu</span>();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>如果要加同一个产品族的话，只需要再加一个对应的工厂类即可，不需要修改其他的类。</p>
<h4 id="4243-优缺点"><a class="markdownIt-Anchor" href="#4243-优缺点">#</a> 4.2.4.3 优缺点</h4>
<p><strong>优点：</strong></p>
<p>当一个产品族中的多个对象被设计成一起工作时，它能保证客户端始终只使用同一个产品族中的对象。</p>
<p><strong>缺点：</strong></p>
<p>当产品族中需要增加一个新的产品时，所有的工厂类都需要进行修改。</p>
<h4 id="4244-使用场景"><a class="markdownIt-Anchor" href="#4244-使用场景">#</a> 4.2.4.4 使用场景</h4>
<ul>
<li>
<p>当需要创建的对象是一系列相互关联或相互依赖的产品族时，如电器工厂中的电视机、洗衣机、空调等。</p>
</li>
<li>
<p>系统中有多个产品族，但每次只使用其中的某一族产品。如有人只喜欢穿某一个品牌的衣服和鞋。</p>
</li>
<li>
<p>系统中提供了产品的类库，且所有产品的接口相同，客户端不依赖产品实例的创建细节和内部结构。</p>
</li>
</ul>
<p>如：输入法换皮肤，一整套一起换。生成不同操作系统的程序。</p>
<h3 id="425-模式扩展"><a class="markdownIt-Anchor" href="#425-模式扩展">#</a> 4.2.5 模式扩展</h3>
<p><strong>简单工厂 + 配置文件解除耦合</strong></p>
<p>可以通过工厂模式 + 配置文件的方式解除工厂对象和产品对象的耦合。在工厂类中加载配置文件中的全类名，并创建对象进行存储，客户端如果需要对象，直接进行获取即可。</p>
<p>第一步：定义配置文件</p>
<p>为了演示方便，我们使用 properties 文件作为配置文件，名称为 bean.properties</p>
<div class="highlight-container" data-rel="Properties"><figure class="iseeu highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">american</span>=<span class="string">com.itheima.pattern.factory.config_factory.AmericanCoffee</span></span><br><span class="line"><span class="attr">latte</span>=<span class="string">com.itheima.pattern.factory.config_factory.LatteCoffee</span></span><br></pre></td></tr></table></figure></div>
<p>第二步：改进工厂类</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">CoffeeFactory</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Map&lt;String,Coffee&gt; map = <span class="keyword">new</span> <span class="title class_">HashMap</span>();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> &#123;</span><br><span class="line">        <span class="type">Properties</span> <span class="variable">p</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Properties</span>();</span><br><span class="line">        <span class="type">InputStream</span> <span class="variable">is</span> <span class="operator">=</span> CoffeeFactory.class.getClassLoader().getResourceAsStream(<span class="string">&quot;bean.properties&quot;</span>);</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            p.load(is);</span><br><span class="line">            <span class="comment">//遍历Properties集合对象</span></span><br><span class="line">            Set&lt;Object&gt; keys = p.keySet();</span><br><span class="line">            <span class="keyword">for</span> (Object key : keys) &#123;</span><br><span class="line">                <span class="comment">//根据键获取值（全类名）</span></span><br><span class="line">                <span class="type">String</span> <span class="variable">className</span> <span class="operator">=</span> p.getProperty((String) key);</span><br><span class="line">                <span class="comment">//获取字节码对象</span></span><br><span class="line">                <span class="type">Class</span> <span class="variable">clazz</span> <span class="operator">=</span> Class.forName(className);</span><br><span class="line">                <span class="type">Coffee</span> <span class="variable">obj</span> <span class="operator">=</span> (Coffee) clazz.newInstance();</span><br><span class="line">                map.put((String)key,obj);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> Coffee <span class="title function_">createCoffee</span><span class="params">(String name)</span> &#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> map.get(name);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>静态成员变量用来存储创建的对象（键存储的是名称，值存储的是对应的对象），而读取配置文件以及创建对象写在静态代码块中，目的就是只需要执行一次。</p>
<h3 id="426-jdk源码解析-collectioniterator方法"><a class="markdownIt-Anchor" href="#426-jdk源码解析-collectioniterator方法">#</a> 4.2.6 JDK 源码解析 - Collection.iterator 方法</h3>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Demo</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        List&lt;String&gt; list = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;&gt;();</span><br><span class="line">        list.add(<span class="string">&quot;令狐冲&quot;</span>);</span><br><span class="line">        list.add(<span class="string">&quot;风清扬&quot;</span>);</span><br><span class="line">        list.add(<span class="string">&quot;任我行&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//获取迭代器对象</span></span><br><span class="line">        Iterator&lt;String&gt; it = list.iterator();</span><br><span class="line">        <span class="comment">//使用迭代器遍历</span></span><br><span class="line">        <span class="keyword">while</span>(it.hasNext()) &#123;</span><br><span class="line">            <span class="type">String</span> <span class="variable">ele</span> <span class="operator">=</span> it.next();</span><br><span class="line">            System.out.println(ele);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>对上面的代码大家应该很熟，使用迭代器遍历集合，获取集合中的元素。而单列集合获取迭代器的方法就使用到了工厂方法模式。我们看通过类图看看结构：<br>
<img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420230516219.png"
                      alt="在这里插入图片描述"
                ></p>
<p>Collection 接口是抽象工厂类，ArrayList 是具体的工厂类；Iterator 接口是抽象商品类，ArrayList 类中的 Iter 内部类是具体的商品类。在具体的工厂类中 iterator () 方法创建具体的商品类的对象。</p>
<blockquote>
<p>另：</p>
<p>1,DateForamt 类中的 getInstance () 方法使用的是工厂模式；</p>
<p>2,Calendar 类中的 getInstance () 方法使用的是工厂模式；</p>
</blockquote>
<h2 id="43-原型模式"><a class="markdownIt-Anchor" href="#43-原型模式">#</a> 4.3 原型模式</h2>
<h3 id="431-概述"><a class="markdownIt-Anchor" href="#431-概述">#</a> 4.3.1 概述</h3>
<p>用一个已经创建的实例作为原型，通过复制该原型对象来创建一个和原型对象相同的新对象。</p>
<h3 id="432-结构"><a class="markdownIt-Anchor" href="#432-结构">#</a> 4.3.2 结构</h3>
<p>原型模式包含如下角色：</p>
<ul>
<li>抽象原型类：规定了具体原型对象必须实现的的 clone () 方法。</li>
<li>具体原型类：实现抽象原型类的 clone () 方法，它是可被复制的对象。</li>
<li>访问类：使用具体原型类中的 clone () 方法来复制新的对象。</li>
</ul>
<p>接口类图如下：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420225344619.png"
                      alt="在这里插入图片描述"
                ></p>
<h3 id="433-实现"><a class="markdownIt-Anchor" href="#433-实现">#</a> 4.3.3 实现</h3>
<p>原型模式的克隆分为浅克隆和深克隆。</p>
<blockquote>
<p>浅克隆：创建一个新对象，新对象的属性和原来对象完全相同，对于非基本类型属性，仍指向原有属性所指向的对象的内存地址。</p>
<p>深克隆：创建一个新对象，属性中引用的其他对象也会被克隆，不再指向原有对象地址。</p>
</blockquote>
<p>Java 中的 Object 类中提供了  <code>clone()</code>  方法来实现浅克隆。 Cloneable 接口是上面的类图中的抽象原型类，而实现了 Cloneable 接口的子实现类就是具体的原型类。代码如下：</p>
<p><strong>Realizetype（具体的原型类）：</strong></p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Realizetype</span> <span class="keyword">implements</span> <span class="title class_">Cloneable</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Realizetype</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;具体的原型对象创建完成！&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> Realizetype <span class="title function_">clone</span><span class="params">()</span> <span class="keyword">throws</span> CloneNotSupportedException &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;具体原型复制成功！&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> (Realizetype) <span class="built_in">super</span>.clone();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><strong>PrototypeTest（测试访问类）：</strong></p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">PrototypeTest</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> CloneNotSupportedException &#123;</span><br><span class="line">        <span class="type">Realizetype</span> <span class="variable">r1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Realizetype</span>();</span><br><span class="line">        <span class="type">Realizetype</span> <span class="variable">r2</span> <span class="operator">=</span> r1.clone();</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;对象r1和r2是同一个对象？&quot;</span> + (r1 == r2));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<h3 id="434-案例"><a class="markdownIt-Anchor" href="#434-案例">#</a> 4.3.4 案例</h3>
<p><strong>用原型模式生成 “三好学生” 奖状</strong></p>
<p>同一学校的 “三好学生” 奖状除了获奖人姓名不同，其他都相同，可以使用原型模式复制多个 “三好学生” 奖状出来，然后在修改奖状上的名字即可。</p>
<p>类图如下：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420230558335.png"
                      alt="在这里插入图片描述"
                ></p>
<p>代码如下：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//奖状类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Citation</span> <span class="keyword">implements</span> <span class="title class_">Cloneable</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setName</span><span class="params">(String name)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getName</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> (<span class="built_in">this</span>.name);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">show</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(name + <span class="string">&quot;同学：在2020学年第一学期中表现优秀，被评为三好学生。特发此状！&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> Citation <span class="title function_">clone</span><span class="params">()</span> <span class="keyword">throws</span> CloneNotSupportedException &#123;</span><br><span class="line">        <span class="keyword">return</span> (Citation) <span class="built_in">super</span>.clone();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//测试访问类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">CitationTest</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> CloneNotSupportedException &#123;</span><br><span class="line">        <span class="type">Citation</span> <span class="variable">c1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Citation</span>();</span><br><span class="line">        c1.setName(<span class="string">&quot;张三&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//复制奖状</span></span><br><span class="line">        <span class="type">Citation</span> <span class="variable">c2</span> <span class="operator">=</span> c1.clone();</span><br><span class="line">        <span class="comment">//将奖状的名字修改李四</span></span><br><span class="line">        c2.setName(<span class="string">&quot;李四&quot;</span>);</span><br><span class="line"></span><br><span class="line">        c1.show();</span><br><span class="line">        c2.show();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<h3 id="435-使用场景"><a class="markdownIt-Anchor" href="#435-使用场景">#</a> 4.3.5 使用场景</h3>
<ul>
<li>对象的创建非常复杂，可以使用原型模式快捷的创建对象。</li>
<li>性能和安全要求比较高。</li>
</ul>
<h3 id="436-扩展深克隆"><a class="markdownIt-Anchor" href="#436-扩展深克隆">#</a> 4.3.6 扩展（深克隆）</h3>
<p>将上面的 “三好学生” 奖状的案例中 Citation 类的 name 属性修改为 Student 类型的属性。代码如下：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//奖状类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Citation</span> <span class="keyword">implements</span> <span class="title class_">Cloneable</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> Student stu;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Student <span class="title function_">getStu</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> stu;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setStu</span><span class="params">(Student stu)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.stu = stu;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">show</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(stu.getName() + <span class="string">&quot;同学：在2020学年第一学期中表现优秀，被评为三好学生。特发此状！&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> Citation <span class="title function_">clone</span><span class="params">()</span> <span class="keyword">throws</span> CloneNotSupportedException &#123;</span><br><span class="line">        <span class="keyword">return</span> (Citation) <span class="built_in">super</span>.clone();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//学生类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Student</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    <span class="keyword">private</span> String address;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Student</span><span class="params">(String name, String address)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.name = name;</span><br><span class="line">        <span class="built_in">this</span>.address = address;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Student</span><span class="params">()</span> &#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getName</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setName</span><span class="params">(String name)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getAddress</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> address;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setAddress</span><span class="params">(String address)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.address = address;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//测试类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">CitationTest</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> CloneNotSupportedException &#123;</span><br><span class="line"></span><br><span class="line">        <span class="type">Citation</span> <span class="variable">c1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Citation</span>();</span><br><span class="line">        <span class="type">Student</span> <span class="variable">stu</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Student</span>(<span class="string">&quot;张三&quot;</span>, <span class="string">&quot;西安&quot;</span>);</span><br><span class="line">        c1.setStu(stu);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//复制奖状</span></span><br><span class="line">        <span class="type">Citation</span> <span class="variable">c2</span> <span class="operator">=</span> c1.clone();</span><br><span class="line">        <span class="comment">//获取c2奖状所属学生对象</span></span><br><span class="line">        <span class="type">Student</span> <span class="variable">stu1</span> <span class="operator">=</span> c2.getStu();</span><br><span class="line">        stu1.setName(<span class="string">&quot;李四&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//判断stu对象和stu1对象是否是同一个对象</span></span><br><span class="line">        System.out.println(<span class="string">&quot;stu和stu1是同一个对象？&quot;</span> + (stu == stu1));</span><br><span class="line"></span><br><span class="line">        c1.show();</span><br><span class="line">        c2.show();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>运行结果为：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420230626476.png"
                      alt="在这里插入图片描述"
                ></p>
<p><font color="red">说明：</font></p>
<pre><code>stu对象和stu1对象是同一个对象，就会产生将stu1对象中name属性值改为“李四”，两个Citation（奖状）对象中显示的都是李四。这就是浅克隆的效果，对具体原型类（Citation）中的引用类型的属性进行引用的复制。这种情况需要使用深克隆，而进行深克隆需要使用对象流。代码如下：
</code></pre>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">CitationTest1</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="type">Citation</span> <span class="variable">c1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Citation</span>();</span><br><span class="line">        <span class="type">Student</span> <span class="variable">stu</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Student</span>(<span class="string">&quot;张三&quot;</span>, <span class="string">&quot;西安&quot;</span>);</span><br><span class="line">        c1.setStu(stu);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建对象输出流对象</span></span><br><span class="line">        <span class="type">ObjectOutputStream</span> <span class="variable">oos</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ObjectOutputStream</span>(<span class="keyword">new</span> <span class="title class_">FileOutputStream</span>(<span class="string">&quot;C:\\Users\\Think\\Desktop\\b.txt&quot;</span>));</span><br><span class="line">        <span class="comment">//将c1对象写出到文件中</span></span><br><span class="line">        oos.writeObject(c1);</span><br><span class="line">        oos.close();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建对象出入流对象</span></span><br><span class="line">        <span class="type">ObjectInputStream</span> <span class="variable">ois</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ObjectInputStream</span>(<span class="keyword">new</span> <span class="title class_">FileInputStream</span>(<span class="string">&quot;C:\\Users\\Think\\Desktop\\b.txt&quot;</span>));</span><br><span class="line">        <span class="comment">//读取对象</span></span><br><span class="line">        <span class="type">Citation</span> <span class="variable">c2</span> <span class="operator">=</span> (Citation) ois.readObject();</span><br><span class="line">        <span class="comment">//获取c2奖状所属学生对象</span></span><br><span class="line">        <span class="type">Student</span> <span class="variable">stu1</span> <span class="operator">=</span> c2.getStu();</span><br><span class="line">        stu1.setName(<span class="string">&quot;李四&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//判断stu对象和stu1对象是否是同一个对象</span></span><br><span class="line">        System.out.println(<span class="string">&quot;stu和stu1是同一个对象？&quot;</span> + (stu == stu1));</span><br><span class="line"></span><br><span class="line">        c1.show();</span><br><span class="line">        c2.show();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>运行结果为：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420230646842.png"
                      alt="在这里插入图片描述"
                ></p>
<blockquote>
<p>注意：Citation 类和 Student 类必须实现 Serializable 接口，否则会抛 NotSerializableException 异常。</p>
</blockquote>
<h2 id="45-建造者模式"><a class="markdownIt-Anchor" href="#45-建造者模式">#</a> 4.5 建造者模式</h2>
<h3 id="441-概述"><a class="markdownIt-Anchor" href="#441-概述">#</a> 4.4.1 概述</h3>
<p>将一个复杂对象的构建与表示分离，使得同样的构建过程可以创建不同的表示。</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420230712930.png"
                      alt="在这里插入图片描述"
                ></p>
<ul>
<li>分离了部件的构造 (由 Builder 来负责) 和装配 (由 Director 负责)。 从而可以构造出复杂的对象。这个模式适用于：某个对象的构建过程复杂的情况。</li>
<li>由于实现了构建和装配的解耦。不同的构建器，相同的装配，也可以做出不同的对象；相同的构建器，不同的装配顺序也可以做出不同的对象。也就是实现了构建算法、装配算法的解耦，实现了更好的复用。</li>
<li>建造者模式可以将部件和其组装过程分开，一步一步创建一个复杂的对象。用户只需要指定复杂对象的类型就可以得到该对象，而无须知道其内部的具体构造细节。</li>
</ul>
<h3 id="442-结构"><a class="markdownIt-Anchor" href="#442-结构">#</a> 4.4.2 结构</h3>
<p>建造者（Builder）模式包含如下角色：</p>
<ul>
<li>
<p>抽象建造者类（Builder）：这个接口规定要实现复杂对象的那些部分的创建，并不涉及具体的部件对象的创建。</p>
</li>
<li>
<p>具体建造者类（ConcreteBuilder）：实现 Builder 接口，完成复杂产品的各个部件的具体创建方法。在构造过程完成后，提供产品的实例。</p>
</li>
<li>
<p>产品类（Product）：要创建的复杂对象。</p>
</li>
<li>
<p>指挥者类（Director）：调用具体建造者来创建复杂对象的各个部分，在指导者中不涉及具体产品的信息，只负责保证对象各部分完整创建或按某种顺序创建。</p>
</li>
</ul>
<p>类图如下：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420230740577.png"
                      alt="在这里插入图片描述"
                ></p>
<h3 id="443-实例"><a class="markdownIt-Anchor" href="#443-实例">#</a> 4.4.3 实例</h3>
<p><strong>创建共享单车</strong></p>
<p>生产自行车是一个复杂的过程，它包含了车架，车座等组件的生产。而车架又有碳纤维，铝合金等材质的，车座有橡胶，真皮等材质。对于自行车的生产就可以使用建造者模式。</p>
<p>这里 Bike 是产品，包含车架，车座等组件；Builder 是抽象建造者，MobikeBuilder 和 OfoBuilder 是具体的建造者；Director 是指挥者。类图如下：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/2021042023075989.png"
                      alt="在这里插入图片描述"
                ></p>
<p>具体的代码如下：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//自行车类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Bike</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> String frame;</span><br><span class="line">    <span class="keyword">private</span> String seat;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getFrame</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> frame;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setFrame</span><span class="params">(String frame)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.frame = frame;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getSeat</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> seat;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setSeat</span><span class="params">(String seat)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.seat = seat;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 抽象 builder 类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title class_">Builder</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">protected</span> <span class="type">Bike</span> <span class="variable">mBike</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Bike</span>();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title function_">buildFrame</span><span class="params">()</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title function_">buildSeat</span><span class="params">()</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">abstract</span> Bike <span class="title function_">createBike</span><span class="params">()</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//摩拜单车Builder类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MobikeBuilder</span> <span class="keyword">extends</span> <span class="title class_">Builder</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">buildFrame</span><span class="params">()</span> &#123;</span><br><span class="line">        mBike.setFrame(<span class="string">&quot;铝合金车架&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">buildSeat</span><span class="params">()</span> &#123;</span><br><span class="line">        mBike.setSeat(<span class="string">&quot;真皮车座&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> Bike <span class="title function_">createBike</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> mBike;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//ofo单车Builder类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">OfoBuilder</span> <span class="keyword">extends</span> <span class="title class_">Builder</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">buildFrame</span><span class="params">()</span> &#123;</span><br><span class="line">        mBike.setFrame(<span class="string">&quot;碳纤维车架&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">buildSeat</span><span class="params">()</span> &#123;</span><br><span class="line">        mBike.setSeat(<span class="string">&quot;橡胶车座&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> Bike <span class="title function_">createBike</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> mBike;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//指挥者类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Director</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> Builder mBuilder;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Director</span><span class="params">(Builder builder)</span> &#123;</span><br><span class="line">        mBuilder = builder;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Bike <span class="title function_">construct</span><span class="params">()</span> &#123;</span><br><span class="line">        mBuilder.buildFrame();</span><br><span class="line">        mBuilder.buildSeat();</span><br><span class="line">        <span class="keyword">return</span> mBuilder.createBike();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//测试类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Client</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        showBike(<span class="keyword">new</span> <span class="title class_">OfoBuilder</span>());</span><br><span class="line">        showBike(<span class="keyword">new</span> <span class="title class_">MobikeBuilder</span>());</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">showBike</span><span class="params">(Builder builder)</span> &#123;</span><br><span class="line">        <span class="type">Director</span> <span class="variable">director</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Director</span>(builder);</span><br><span class="line">        <span class="type">Bike</span> <span class="variable">bike</span> <span class="operator">=</span> director.construct();</span><br><span class="line">        System.out.println(bike.getFrame());</span><br><span class="line">        System.out.println(bike.getSeat());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><strong>注意：</strong></p>
<p>上面示例是 Builder 模式的常规用法，指挥者类 Director 在建造者模式中具有很重要的作用，它用于指导具体构建者如何构建产品，控制调用先后次序，并向调用者返回完整的产品类，但是有些情况下需要简化系统结构，可以把指挥者类和抽象建造者进行结合</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 抽象 builder 类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title class_">Builder</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">protected</span> <span class="type">Bike</span> <span class="variable">mBike</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Bike</span>();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title function_">buildFrame</span><span class="params">()</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title function_">buildSeat</span><span class="params">()</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">abstract</span> Bike <span class="title function_">createBike</span><span class="params">()</span>;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">public</span> Bike <span class="title function_">construct</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.buildFrame();</span><br><span class="line">        <span class="built_in">this</span>.BuildSeat();</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span>.createBike();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><strong>说明：</strong></p>
<p>这样做确实简化了系统结构，但同时也加重了抽象建造者类的职责，也不是太符合单一职责原则，如果 construct () 过于复杂，建议还是封装到 Director 中。</p>
<h3 id="444-优缺点"><a class="markdownIt-Anchor" href="#444-优缺点">#</a> 4.4.4 优缺点</h3>
<p><strong>优点：</strong></p>
<ul>
<li>建造者模式的封装性很好。使用建造者模式可以有效的封装变化，在使用建造者模式的场景中，一般产品类和建造者类是比较稳定的，因此，将主要的业务逻辑封装在指挥者类中对整体而言可以取得比较好的稳定性。</li>
<li>在建造者模式中，客户端不必知道产品内部组成的细节，将产品本身与产品的创建过程解耦，使得相同的创建过程可以创建不同的产品对象。</li>
<li>可以更加精细地控制产品的创建过程 。将复杂产品的创建步骤分解在不同的方法中，使得创建过程更加清晰，也更方便使用程序来控制创建过程。</li>
<li>建造者模式很容易进行扩展。如果有新的需求，通过实现一个新的建造者类就可以完成，基本上不用修改之前已经测试通过的代码，因此也就不会对原有功能引入风险。符合开闭原则。</li>
</ul>
<p><strong>缺点：</strong></p>
<p>造者模式所创建的产品一般具有较多的共同点，其组成部分相似，如果产品之间的差异性很大，则不适合使用建造者模式，因此其使用范围受到一定的限制。</p>
<h3 id="445-使用场景"><a class="markdownIt-Anchor" href="#445-使用场景">#</a> 4.4.5 使用场景</h3>
<p>建造者（Builder）模式创建的是复杂对象，其产品的各个部分经常面临着剧烈的变化，但将它们组合在一起的算法却相对稳定，所以它通常在以下场合使用。</p>
<ul>
<li>创建的对象较复杂，由多个部件构成，各部件面临着复杂的变化，但构件间的建造顺序是稳定的。</li>
<li>创建复杂对象的算法独立于该对象的组成部分以及它们的装配方式，即产品的构建过程和最终的表示是独立的。</li>
</ul>
<h3 id="446-模式扩展"><a class="markdownIt-Anchor" href="#446-模式扩展">#</a> 4.4.6 模式扩展</h3>
<p>建造者模式除了上面的用途外，在开发中还有一个常用的使用方式，就是当一个类构造器需要传入很多参数时，如果创建这个类的实例，代码可读性会非常差，而且很容易引入错误，此时就可以利用建造者模式进行重构。</p>
<p>重构前代码如下：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Phone</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> String cpu;</span><br><span class="line">    <span class="keyword">private</span> String screen;</span><br><span class="line">    <span class="keyword">private</span> String memory;</span><br><span class="line">    <span class="keyword">private</span> String mainboard;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Phone</span><span class="params">(String cpu, String screen, String memory, String mainboard)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.cpu = cpu;</span><br><span class="line">        <span class="built_in">this</span>.screen = screen;</span><br><span class="line">        <span class="built_in">this</span>.memory = memory;</span><br><span class="line">        <span class="built_in">this</span>.mainboard = mainboard;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getCpu</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> cpu;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setCpu</span><span class="params">(String cpu)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.cpu = cpu;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getScreen</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> screen;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setScreen</span><span class="params">(String screen)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.screen = screen;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getMemory</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> memory;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setMemory</span><span class="params">(String memory)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.memory = memory;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getMainboard</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> mainboard;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setMainboard</span><span class="params">(String mainboard)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.mainboard = mainboard;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">toString</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;Phone&#123;&quot;</span> +</span><br><span class="line">                <span class="string">&quot;cpu=&#x27;&quot;</span> + cpu + <span class="string">&#x27;\&#x27;&#x27;</span> +</span><br><span class="line">                <span class="string">&quot;, screen=&#x27;&quot;</span> + screen + <span class="string">&#x27;\&#x27;&#x27;</span> +</span><br><span class="line">                <span class="string">&quot;, memory=&#x27;&quot;</span> + memory + <span class="string">&#x27;\&#x27;&#x27;</span> +</span><br><span class="line">                <span class="string">&quot;, mainboard=&#x27;&quot;</span> + mainboard + <span class="string">&#x27;\&#x27;&#x27;</span> +</span><br><span class="line">                <span class="string">&#x27;&#125;&#x27;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Client</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="comment">//构建Phone对象</span></span><br><span class="line">        <span class="type">Phone</span> <span class="variable">phone</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Phone</span>(<span class="string">&quot;intel&quot;</span>,<span class="string">&quot;三星屏幕&quot;</span>,<span class="string">&quot;金士顿&quot;</span>,<span class="string">&quot;华硕&quot;</span>);</span><br><span class="line">        System.out.println(phone);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>上面在客户端代码中构建 Phone 对象，传递了四个参数，如果参数更多呢？代码的可读性及使用的成本就是比较高。</p>
<p>重构后代码：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Phone</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> String cpu;</span><br><span class="line">    <span class="keyword">private</span> String screen;</span><br><span class="line">    <span class="keyword">private</span> String memory;</span><br><span class="line">    <span class="keyword">private</span> String mainboard;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="title function_">Phone</span><span class="params">(Builder builder)</span> &#123;</span><br><span class="line">        cpu = builder.cpu;</span><br><span class="line">        screen = builder.screen;</span><br><span class="line">        memory = builder.memory;</span><br><span class="line">        mainboard = builder.mainboard;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">class</span> <span class="title class_">Builder</span> &#123;</span><br><span class="line">        <span class="keyword">private</span> String cpu;</span><br><span class="line">        <span class="keyword">private</span> String screen;</span><br><span class="line">        <span class="keyword">private</span> String memory;</span><br><span class="line">        <span class="keyword">private</span> String mainboard;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">public</span> <span class="title function_">Builder</span><span class="params">()</span> &#123;&#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">public</span> Builder <span class="title function_">cpu</span><span class="params">(String val)</span> &#123;</span><br><span class="line">            cpu = val;</span><br><span class="line">            <span class="keyword">return</span> <span class="built_in">this</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">public</span> Builder <span class="title function_">screen</span><span class="params">(String val)</span> &#123;</span><br><span class="line">            screen = val;</span><br><span class="line">            <span class="keyword">return</span> <span class="built_in">this</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">public</span> Builder <span class="title function_">memory</span><span class="params">(String val)</span> &#123;</span><br><span class="line">            memory = val;</span><br><span class="line">            <span class="keyword">return</span> <span class="built_in">this</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">public</span> Builder <span class="title function_">mainboard</span><span class="params">(String val)</span> &#123;</span><br><span class="line">            mainboard = val;</span><br><span class="line">            <span class="keyword">return</span> <span class="built_in">this</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">public</span> Phone <span class="title function_">build</span><span class="params">()</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Phone</span>(<span class="built_in">this</span>);&#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">toString</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;Phone&#123;&quot;</span> +</span><br><span class="line">                <span class="string">&quot;cpu=&#x27;&quot;</span> + cpu + <span class="string">&#x27;\&#x27;&#x27;</span> +</span><br><span class="line">                <span class="string">&quot;, screen=&#x27;&quot;</span> + screen + <span class="string">&#x27;\&#x27;&#x27;</span> +</span><br><span class="line">                <span class="string">&quot;, memory=&#x27;&quot;</span> + memory + <span class="string">&#x27;\&#x27;&#x27;</span> +</span><br><span class="line">                <span class="string">&quot;, mainboard=&#x27;&quot;</span> + mainboard + <span class="string">&#x27;\&#x27;&#x27;</span> +</span><br><span class="line">                <span class="string">&#x27;&#125;&#x27;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Client</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">Phone</span> <span class="variable">phone</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Phone</span>.Builder()</span><br><span class="line">                .cpu(<span class="string">&quot;intel&quot;</span>)</span><br><span class="line">                .mainboard(<span class="string">&quot;华硕&quot;</span>)</span><br><span class="line">                .memory(<span class="string">&quot;金士顿&quot;</span>)</span><br><span class="line">                .screen(<span class="string">&quot;三星&quot;</span>)</span><br><span class="line">                .build();</span><br><span class="line">        System.out.println(phone);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>重构后的代码在使用起来更方便，某种程度上也可以提高开发效率。从软件设计上，对程序员的要求比较高。</p>
<h2 id="46-创建者模式对比"><a class="markdownIt-Anchor" href="#46-创建者模式对比">#</a> 4.6 创建者模式对比</h2>
<h3 id="461-工厂方法模式vs建造者模式"><a class="markdownIt-Anchor" href="#461-工厂方法模式vs建造者模式">#</a> 4.6.1 工厂方法模式 VS 建造者模式</h3>
<p>工厂方法模式注重的是整体对象的创建方式；而建造者模式注重的是部件构建的过程，意在通过一步一步地精确构造创建出一个复杂的对象。</p>
<p>我们举个简单例子来说明两者的差异，如要制造一个超人，如果使用工厂方法模式，直接产生出来的就是一个力大无穷、能够飞翔、内裤外穿的超人；而如果使用建造者模式，则需要组装手、头、脚、躯干等部分，然后再把内裤外穿，于是一个超人就诞生了。</p>
<h3 id="462-抽象工厂模式vs建造者模式"><a class="markdownIt-Anchor" href="#462-抽象工厂模式vs建造者模式">#</a> 4.6.2 抽象工厂模式 VS 建造者模式</h3>
<p>抽象工厂模式实现对产品家族的创建，一个产品家族是这样的一系列产品：具有不同分类维度的产品组合，采用抽象工厂模式则是不需要关心构建过程，只关心什么产品由什么工厂生产即可。</p>
<p>建造者模式则是要求按照指定的蓝图建造产品，它的主要目的是通过组装零配件而产生一个新产品。</p>
<p>如果将抽象工厂模式看成汽车配件生产工厂，生产一个产品族的产品，那么建造者模式就是一个汽车组装工厂，通过对部件的组装可以返回一辆完整的汽车。</p>
<h1 id="5结构型模式"><a class="markdownIt-Anchor" href="#5结构型模式">#</a> 5，结构型模式</h1>
<p>结构型模式描述如何将类或对象按某种布局组成更大的结构。它分为类结构型模式和对象结构型模式，前者采用继承机制来组织接口和类，后者釆用组合或聚合来组合对象。</p>
<p>由于组合关系或聚合关系比继承关系耦合度低，满足 “合成复用原则”，所以对象结构型模式比类结构型模式具有更大的灵活性。</p>
<p>结构型模式分为以下 7 种：</p>
<ul>
<li>代理模式</li>
<li>适配器模式</li>
<li>装饰者模式</li>
<li>桥接模式</li>
<li>外观模式</li>
<li>组合模式</li>
<li>享元模式</li>
</ul>
<h2 id="51-代理模式"><a class="markdownIt-Anchor" href="#51-代理模式">#</a> 5.1 代理模式</h2>
<h3 id="511-概述"><a class="markdownIt-Anchor" href="#511-概述">#</a> 5.1.1 概述</h3>
<p>由于某些原因需要给某对象提供一个代理以控制对该对象的访问。这时，访问对象不适合或者不能直接引用目标对象，代理对象作为访问对象和目标对象之间的中介。</p>
<p>Java 中的代理按照代理类生成时机不同又分为静态代理和动态代理。静态代理代理类在编译期就生成，而动态代理代理类则是在 Java 运行时动态生成。动态代理又有 JDK 代理和 CGLib 代理两种。</p>
<h3 id="512-结构"><a class="markdownIt-Anchor" href="#512-结构">#</a> 5.1.2 结构</h3>
<p>代理（Proxy）模式分为三种角色：</p>
<ul>
<li>抽象主题（Subject）类： 通过接口或抽象类声明真实主题和代理对象实现的业务方法。</li>
<li>真实主题（Real Subject）类： 实现了抽象主题中的具体业务，是代理对象所代表的真实对象，是最终要引用的对象。</li>
<li>代理（Proxy）类 ： 提供了与真实主题相同的接口，其内部含有对真实主题的引用，它可以访问、控制或扩展真实主题的功能。</li>
</ul>
<h3 id="513-静态代理"><a class="markdownIt-Anchor" href="#513-静态代理">#</a> 5.1.3 静态代理</h3>
<p>我们通过案例来感受一下静态代理。</p>
<p>【例】火车站卖票</p>
<p>如果要买火车票的话，需要去火车站买票，坐车到火车站，排队等一系列的操作，显然比较麻烦。而火车站在多个地方都有代售点，我们去代售点买票就方便很多了。这个例子其实就是典型的代理模式，火车站是目标对象，代售点是代理对象。类图如下：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420230823544.png"
                      alt="在这里插入图片描述"
                ></p>
<p>代码如下：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//卖票接口</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">SellTickets</span> &#123;</span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">sell</span><span class="params">()</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//火车站  火车站具有卖票功能，所以需要实现SellTickets接口</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TrainStation</span> <span class="keyword">implements</span> <span class="title class_">SellTickets</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">sell</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;火车站卖票&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//代售点</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ProxyPoint</span> <span class="keyword">implements</span> <span class="title class_">SellTickets</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="type">TrainStation</span> <span class="variable">station</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">TrainStation</span>();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">sell</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;代理点收取一些服务费用&quot;</span>);</span><br><span class="line">        station.sell();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//测试类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Client</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">ProxyPoint</span> <span class="variable">pp</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ProxyPoint</span>();</span><br><span class="line">        pp.sell();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>从上面代码中可以看出测试类直接访问的是 ProxyPoint 类对象，也就是说 ProxyPoint 作为访问对象和目标对象的中介。同时也对 sell 方法进行了增强（代理点收取一些服务费用）。</p>
<h3 id="514-jdk动态代理"><a class="markdownIt-Anchor" href="#514-jdk动态代理">#</a> 5.1.4 JDK 动态代理</h3>
<p>接下来我们使用动态代理实现上面案例，先说说 JDK 提供的动态代理。Java 中提供了一个动态代理类 Proxy，Proxy 并不是我们上述所说的代理对象的类，而是提供了一个创建代理对象的静态方法（newProxyInstance 方法）来获取代理对象。</p>
<p>代码如下：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//卖票接口</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">SellTickets</span> &#123;</span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">sell</span><span class="params">()</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//火车站  火车站具有卖票功能，所以需要实现SellTickets接口</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TrainStation</span> <span class="keyword">implements</span> <span class="title class_">SellTickets</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">sell</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;火车站卖票&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//代理工厂，用来创建代理对象</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ProxyFactory</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="type">TrainStation</span> <span class="variable">station</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">TrainStation</span>();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> SellTickets <span class="title function_">getProxyObject</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="comment">//使用Proxy获取代理对象</span></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">            newProxyInstance()方法参数说明：</span></span><br><span class="line"><span class="comment">                ClassLoader loader ： 类加载器，用于加载代理类，使用真实对象的类加载器即可</span></span><br><span class="line"><span class="comment">                Class&lt;?&gt;[] interfaces ： 真实对象所实现的接口，代理模式真实对象和代理对象实现相同的接口</span></span><br><span class="line"><span class="comment">                InvocationHandler h ： 代理对象的调用处理程序</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="type">SellTickets</span> <span class="variable">sellTickets</span> <span class="operator">=</span> (SellTickets) Proxy.newProxyInstance(station.getClass().getClassLoader(),</span><br><span class="line">                station.getClass().getInterfaces(),</span><br><span class="line">                <span class="keyword">new</span> <span class="title class_">InvocationHandler</span>() &#123;</span><br><span class="line">                    <span class="comment">/*</span></span><br><span class="line"><span class="comment">                        InvocationHandler中invoke方法参数说明：</span></span><br><span class="line"><span class="comment">                            proxy ： 代理对象</span></span><br><span class="line"><span class="comment">                            method ： 对应于在代理对象上调用的接口方法的 Method 实例</span></span><br><span class="line"><span class="comment">                            args ： 代理对象调用接口方法时传递的实际参数</span></span><br><span class="line"><span class="comment">                     */</span></span><br><span class="line">                    <span class="keyword">public</span> Object <span class="title function_">invoke</span><span class="params">(Object proxy, Method method, Object[] args)</span> <span class="keyword">throws</span> Throwable &#123;</span><br><span class="line"></span><br><span class="line">                        System.out.println(<span class="string">&quot;代理点收取一些服务费用(JDK动态代理方式)&quot;</span>);</span><br><span class="line">                        <span class="comment">//执行真实对象</span></span><br><span class="line">                        <span class="type">Object</span> <span class="variable">result</span> <span class="operator">=</span> method.invoke(station, args);</span><br><span class="line">                        <span class="keyword">return</span> result;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;);</span><br><span class="line">        <span class="keyword">return</span> sellTickets;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//测试类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Client</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="comment">//获取代理对象</span></span><br><span class="line">        <span class="type">ProxyFactory</span> <span class="variable">factory</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ProxyFactory</span>();</span><br><span class="line">        </span><br><span class="line">        <span class="type">SellTickets</span> <span class="variable">proxyObject</span> <span class="operator">=</span> factory.getProxyObject();</span><br><span class="line">        proxyObject.sell();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><font color="red">使用了动态代理，我们思考下面问题：</font></p>
<ul>
<li>
<p>ProxyFactory 是代理类吗？</p>
<p>ProxyFactory 不是代理模式中所说的代理类，而代理类是程序在运行过程中动态的在内存中生成的类。通过阿里巴巴开源的 Java 诊断工具（Arthas【阿尔萨斯】）查看代理类的结构：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.sun.proxy;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.itheima.proxy.dynamic.jdk.SellTickets;</span><br><span class="line"><span class="keyword">import</span> java.lang.reflect.InvocationHandler;</span><br><span class="line"><span class="keyword">import</span> java.lang.reflect.Method;</span><br><span class="line"><span class="keyword">import</span> java.lang.reflect.Proxy;</span><br><span class="line"><span class="keyword">import</span> java.lang.reflect.UndeclaredThrowableException;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">class</span> <span class="title class_">$Proxy0</span> <span class="keyword">extends</span> <span class="title class_">Proxy</span> <span class="keyword">implements</span> <span class="title class_">SellTickets</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Method m1;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Method m2;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Method m3;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Method m0;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> $Proxy0(InvocationHandler invocationHandler) &#123;</span><br><span class="line">        <span class="built_in">super</span>(invocationHandler);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            m1 = Class.forName(<span class="string">&quot;java.lang.Object&quot;</span>).getMethod(<span class="string">&quot;equals&quot;</span>, Class.forName(<span class="string">&quot;java.lang.Object&quot;</span>));</span><br><span class="line">            m2 = Class.forName(<span class="string">&quot;java.lang.Object&quot;</span>).getMethod(<span class="string">&quot;toString&quot;</span>, <span class="keyword">new</span> <span class="title class_">Class</span>[<span class="number">0</span>]);</span><br><span class="line">            m3 = Class.forName(<span class="string">&quot;com.itheima.proxy.dynamic.jdk.SellTickets&quot;</span>).getMethod(<span class="string">&quot;sell&quot;</span>, <span class="keyword">new</span> <span class="title class_">Class</span>[<span class="number">0</span>]);</span><br><span class="line">            m0 = Class.forName(<span class="string">&quot;java.lang.Object&quot;</span>).getMethod(<span class="string">&quot;hashCode&quot;</span>, <span class="keyword">new</span> <span class="title class_">Class</span>[<span class="number">0</span>]);</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span> (NoSuchMethodException noSuchMethodException) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">NoSuchMethodError</span>(noSuchMethodException.getMessage());</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span> (ClassNotFoundException classNotFoundException) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">NoClassDefFoundError</span>(classNotFoundException.getMessage());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> <span class="type">boolean</span> <span class="title function_">equals</span><span class="params">(Object object)</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> (Boolean)<span class="built_in">this</span>.h.invoke(<span class="built_in">this</span>, m1, <span class="keyword">new</span> <span class="title class_">Object</span>[]&#123;object&#125;);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span> (Error | RuntimeException throwable) &#123;</span><br><span class="line">            <span class="keyword">throw</span> throwable;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span> (Throwable throwable) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">UndeclaredThrowableException</span>(throwable);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> String <span class="title function_">toString</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> (String)<span class="built_in">this</span>.h.invoke(<span class="built_in">this</span>, m2, <span class="literal">null</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span> (Error | RuntimeException throwable) &#123;</span><br><span class="line">            <span class="keyword">throw</span> throwable;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span> (Throwable throwable) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">UndeclaredThrowableException</span>(throwable);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> <span class="type">int</span> <span class="title function_">hashCode</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> (Integer)<span class="built_in">this</span>.h.invoke(<span class="built_in">this</span>, m0, <span class="literal">null</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span> (Error | RuntimeException throwable) &#123;</span><br><span class="line">            <span class="keyword">throw</span> throwable;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span> (Throwable throwable) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">UndeclaredThrowableException</span>(throwable);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title function_">sell</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="built_in">this</span>.h.invoke(<span class="built_in">this</span>, m3, <span class="literal">null</span>);</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span> (Error | RuntimeException throwable) &#123;</span><br><span class="line">            <span class="keyword">throw</span> throwable;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span> (Throwable throwable) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">UndeclaredThrowableException</span>(throwable);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>从上面的类中，我们可以看到以下几个信息：</p>
<ul>
<li>代理类（$Proxy0）实现了 SellTickets。这也就印证了我们之前说的真实类和代理类实现同样的接口。</li>
<li>代理类（$Proxy0）将我们提供了的匿名内部类对象传递给了父类。</li>
</ul>
</li>
<li>
<p>动态代理的执行流程是什么样？</p>
<p>下面是摘取的重点代码：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//程序运行过程中动态生成的代理类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">class</span> <span class="title class_">$Proxy0</span> <span class="keyword">extends</span> <span class="title class_">Proxy</span> <span class="keyword">implements</span> <span class="title class_">SellTickets</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Method m3;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> $Proxy0(InvocationHandler invocationHandler) &#123;</span><br><span class="line">        <span class="built_in">super</span>(invocationHandler);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> &#123;</span><br><span class="line">        m3 = Class.forName(<span class="string">&quot;com.itheima.proxy.dynamic.jdk.SellTickets&quot;</span>).getMethod(<span class="string">&quot;sell&quot;</span>, <span class="keyword">new</span> <span class="title class_">Class</span>[<span class="number">0</span>]);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title function_">sell</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.h.invoke(<span class="built_in">this</span>, m3, <span class="literal">null</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//Java提供的动态代理相关类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Proxy</span> <span class="keyword">implements</span> <span class="title class_">java</span>.io.Serializable &#123;</span><br><span class="line">	<span class="keyword">protected</span> InvocationHandler h;</span><br><span class="line">	 </span><br><span class="line">	<span class="keyword">protected</span> <span class="title function_">Proxy</span><span class="params">(InvocationHandler h)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.h = h;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//代理工厂类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ProxyFactory</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="type">TrainStation</span> <span class="variable">station</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">TrainStation</span>();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> SellTickets <span class="title function_">getProxyObject</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">SellTickets</span> <span class="variable">sellTickets</span> <span class="operator">=</span> (SellTickets) Proxy.newProxyInstance(station.getClass().getClassLoader(),</span><br><span class="line">                station.getClass().getInterfaces(),</span><br><span class="line">                <span class="keyword">new</span> <span class="title class_">InvocationHandler</span>() &#123;</span><br><span class="line">                    </span><br><span class="line">                    <span class="keyword">public</span> Object <span class="title function_">invoke</span><span class="params">(Object proxy, Method method, Object[] args)</span> <span class="keyword">throws</span> Throwable &#123;</span><br><span class="line"></span><br><span class="line">                        System.out.println(<span class="string">&quot;代理点收取一些服务费用(JDK动态代理方式)&quot;</span>);</span><br><span class="line">                        <span class="type">Object</span> <span class="variable">result</span> <span class="operator">=</span> method.invoke(station, args);</span><br><span class="line">                        <span class="keyword">return</span> result;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;);</span><br><span class="line">        <span class="keyword">return</span> sellTickets;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//测试访问类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Client</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="comment">//获取代理对象</span></span><br><span class="line">        <span class="type">ProxyFactory</span> <span class="variable">factory</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ProxyFactory</span>();</span><br><span class="line">        <span class="type">SellTickets</span> <span class="variable">proxyObject</span> <span class="operator">=</span> factory.getProxyObject();</span><br><span class="line">        proxyObject.sell();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
</li>
</ul>
<p>执行流程如下：</p>
<pre><code>1. 在测试类中通过代理对象调用sell()方法
2. 根据多态的特性，执行的是代理类（$Proxy0）中的sell()方法
3. 代理类（$Proxy0）中的sell()方法中又调用了InvocationHandler接口的子实现类对象的invoke方法
4. invoke方法通过反射执行了真实对象所属类(TrainStation)中的sell()方法
</code></pre>
<h3 id="515-cglib动态代理"><a class="markdownIt-Anchor" href="#515-cglib动态代理">#</a> 5.1.5 CGLIB 动态代理</h3>
<p>同样是上面的案例，我们再次使用 CGLIB 代理实现。</p>
<p>如果没有定义 SellTickets 接口，只定义了 TrainStation (火车站类)。很显然 JDK 代理是无法使用了，因为 JDK 动态代理要求必须定义接口，对接口进行代理。</p>
<p>CGLIB 是一个功能强大，高性能的代码生成包。它为没有实现接口的类提供代理，为 JDK 的动态代理提供了很好的补充。</p>
<p>CGLIB 是第三方提供的包，所以需要引入 jar 包的坐标：</p>
<div class="highlight-container" data-rel="Xml"><figure class="iseeu highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>cglib<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>cglib<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.2.2<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure></div>
<p>代码如下：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//火车站</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TrainStation</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">sell</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;火车站卖票&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//代理工厂</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ProxyFactory</span> <span class="keyword">implements</span> <span class="title class_">MethodInterceptor</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="type">TrainStation</span> <span class="variable">target</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">TrainStation</span>();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> TrainStation <span class="title function_">getProxyObject</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="comment">//创建Enhancer对象，类似于JDK动态代理的Proxy类，下一步就是设置几个参数</span></span><br><span class="line">        <span class="type">Enhancer</span> <span class="variable">enhancer</span> <span class="operator">=</span><span class="keyword">new</span> <span class="title class_">Enhancer</span>();</span><br><span class="line">        <span class="comment">//设置父类的字节码对象</span></span><br><span class="line">        enhancer.setSuperclass(target.getClass());</span><br><span class="line">        <span class="comment">//设置回调函数</span></span><br><span class="line">        enhancer.setCallback(<span class="built_in">this</span>);</span><br><span class="line">        <span class="comment">//创建代理对象</span></span><br><span class="line">        <span class="type">TrainStation</span> <span class="variable">obj</span> <span class="operator">=</span> (TrainStation) enhancer.create();</span><br><span class="line">        <span class="keyword">return</span> obj;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">        intercept方法参数说明：</span></span><br><span class="line"><span class="comment">            o ： 代理对象</span></span><br><span class="line"><span class="comment">            method ： 真实对象中的方法的Method实例</span></span><br><span class="line"><span class="comment">            args ： 实际参数</span></span><br><span class="line"><span class="comment">            methodProxy ：代理对象中的方法的method实例</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> TrainStation <span class="title function_">intercept</span><span class="params">(Object o, Method method, Object[] args, MethodProxy methodProxy)</span> <span class="keyword">throws</span> Throwable &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;代理点收取一些服务费用(CGLIB动态代理方式)&quot;</span>);</span><br><span class="line">        <span class="type">TrainStation</span> <span class="variable">result</span> <span class="operator">=</span> (TrainStation) methodProxy.invokeSuper(o, args);</span><br><span class="line">        <span class="keyword">return</span> result;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//测试类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Client</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="comment">//创建代理工厂对象</span></span><br><span class="line">        <span class="type">ProxyFactory</span> <span class="variable">factory</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ProxyFactory</span>();</span><br><span class="line">        <span class="comment">//获取代理对象</span></span><br><span class="line">        <span class="type">TrainStation</span> <span class="variable">proxyObject</span> <span class="operator">=</span> factory.getProxyObject();</span><br><span class="line"></span><br><span class="line">        proxyObject.sell();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<h3 id="516-三种代理的对比"><a class="markdownIt-Anchor" href="#516-三种代理的对比">#</a> 5.1.6 三种代理的对比</h3>
<ul>
<li>
<p>jdk 代理和 CGLIB 代理</p>
<p>使用 CGLib 实现动态代理，CGLib 底层采用 ASM 字节码生成框架，使用字节码技术生成代理类，在 JDK1.6 之前比使用 Java 反射效率要高。唯一需要注意的是，CGLib 不能对声明为 final 的类或者方法进行代理，因为 CGLib 原理是动态生成被代理类的子类。</p>
<p>在 JDK1.6、JDK1.7、JDK1.8 逐步对 JDK 动态代理优化之后，在调用次数较少的情况下，JDK 代理效率高于 CGLib 代理效率，只有当进行大量调用的时候，JDK1.6 和 JDK1.7 比 CGLib 代理效率低一点，但是到 JDK1.8 的时候，JDK 代理效率高于 CGLib 代理。所以如果有接口使用 JDK 动态代理，如果没有接口使用 CGLIB 代理。</p>
</li>
<li>
<p>动态代理和静态代理</p>
<p>动态代理与静态代理相比较，最大的好处是接口中声明的所有方法都被转移到调用处理器一个集中的方法中处理（InvocationHandler.invoke）。这样，在接口方法数量比较多的时候，我们可以进行灵活处理，而不需要像静态代理那样每一个方法进行中转。</p>
<p>如果接口增加一个方法，静态代理模式除了所有实现类需要实现这个方法外，所有代理类也需要实现此方法。增加了代码维护的复杂度。而动态代理不会出现该问题</p>
</li>
</ul>
<h3 id="517-优缺点"><a class="markdownIt-Anchor" href="#517-优缺点">#</a> 5.1.7 优缺点</h3>
<p><strong>优点：</strong></p>
<ul>
<li>代理模式在客户端与目标对象之间起到一个中介作用和保护目标对象的作用；</li>
<li>代理对象可以扩展目标对象的功能；</li>
<li>代理模式能将客户端与目标对象分离，在一定程度上降低了系统的耦合度；</li>
</ul>
<p><strong>缺点：</strong></p>
<ul>
<li>增加了系统的复杂度；</li>
</ul>
<h3 id="518-使用场景"><a class="markdownIt-Anchor" href="#518-使用场景">#</a> 5.1.8 使用场景</h3>
<ul>
<li>
<p>远程（Remote）代理</p>
<p>本地服务通过网络请求远程服务。为了实现本地到远程的通信，我们需要实现网络通信，处理其中可能的异常。为良好的代码设计和可维护性，我们将网络通信部分隐藏起来，只暴露给本地服务一个接口，通过该接口即可访问远程服务提供的功能，而不必过多关心通信部分的细节。</p>
</li>
<li>
<p>防火墙（Firewall）代理</p>
<p>当你将浏览器配置成使用代理功能时，防火墙就将你的浏览器的请求转给互联网；当互联网返回响应时，代理服务器再把它转给你的浏览器。</p>
</li>
<li>
<p>保护（Protect or Access）代理</p>
<p>控制对一个对象的访问，如果需要，可以给不同的用户提供不同级别的使用权限。</p>
</li>
</ul>
<h2 id="52-适配器模式"><a class="markdownIt-Anchor" href="#52-适配器模式">#</a> 5.2 适配器模式</h2>
<h3 id="521-概述"><a class="markdownIt-Anchor" href="#521-概述">#</a> 5.2.1 概述</h3>
<p>如果去欧洲国家去旅游的话，他们的插座如下图最左边，是欧洲标准。而我们使用的插头如下图最右边的。因此我们的笔记本电脑，手机在当地不能直接充电。所以就需要一个插座转换器，转换器第 1 面插入当地的插座，第 2 面供我们充电，这样使得我们的插头在当地能使用。生活中这样的例子很多，手机充电器（将 220v 转换为 5v 的电压），读卡器等，其实就是使用到了适配器模式。</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420225505709.png"
                      alt="在这里插入图片描述"
                ></p>
<p><strong>定义：</strong></p>
<pre><code>将一个类的接口转换成客户希望的另外一个接口，使得原本由于接口不兼容而不能一起工作的那些类能一起工作。

适配器模式分为类适配器模式和对象适配器模式，前者类之间的耦合度比后者高，且要求程序员了解现有组件库中的相关组件的内部结构，所以应用相对较少些。
</code></pre>
<h3 id="522-结构"><a class="markdownIt-Anchor" href="#522-结构">#</a> 5.2.2 结构</h3>
<p>适配器模式（Adapter）包含以下主要角色：</p>
<ul>
<li>目标（Target）接口：当前系统业务所期待的接口，它可以是抽象类或接口。</li>
<li>适配者（Adaptee）类：它是被访问和适配的现存组件库中的组件接口。</li>
<li>适配器（Adapter）类：它是一个转换器，通过继承或引用适配者的对象，把适配者接口转换成目标接口，让客户按目标接口的格式访问适配者。</li>
</ul>
<h3 id="523-类适配器模式"><a class="markdownIt-Anchor" href="#523-类适配器模式">#</a> 5.2.3 类适配器模式</h3>
<p>实现方式：定义一个适配器类来实现当前系统的业务接口，同时又继承现有组件库中已经存在的组件。</p>
<p>【例】读卡器</p>
<p>现有一台电脑只能读取 SD 卡，而要读取 TF 卡中的内容的话就需要使用到适配器模式。创建一个读卡器，将 TF 卡中的内容读取出来。</p>
<p>类图如下：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420230858629.png"
                      alt="在这里插入图片描述"
                ></p>
<p>代码如下：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//SD卡的接口</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">SDCard</span> &#123;</span><br><span class="line">    <span class="comment">//读取SD卡方法</span></span><br><span class="line">    String <span class="title function_">readSD</span><span class="params">()</span>;</span><br><span class="line">    <span class="comment">//写入SD卡功能</span></span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">writeSD</span><span class="params">(String msg)</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//SD卡实现类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">SDCardImpl</span> <span class="keyword">implements</span> <span class="title class_">SDCard</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">readSD</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">String</span> <span class="variable">msg</span> <span class="operator">=</span> <span class="string">&quot;sd card read a msg :hello word SD&quot;</span>;</span><br><span class="line">        <span class="keyword">return</span> msg;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">writeSD</span><span class="params">(String msg)</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;sd card write msg : &quot;</span> + msg);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//电脑类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Computer</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">readSD</span><span class="params">(SDCard sdCard)</span> &#123;</span><br><span class="line">        <span class="keyword">if</span>(sdCard == <span class="literal">null</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">NullPointerException</span>(<span class="string">&quot;sd card null&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> sdCard.readSD();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//TF卡接口</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">TFCard</span> &#123;</span><br><span class="line">    <span class="comment">//读取TF卡方法</span></span><br><span class="line">    String <span class="title function_">readTF</span><span class="params">()</span>;</span><br><span class="line">    <span class="comment">//写入TF卡功能</span></span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">writeTF</span><span class="params">(String msg)</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//TF卡实现类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TFCardImpl</span> <span class="keyword">implements</span> <span class="title class_">TFCard</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">readTF</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">String</span> <span class="variable">msg</span> <span class="operator">=</span><span class="string">&quot;tf card read msg : hello word tf card&quot;</span>;</span><br><span class="line">        <span class="keyword">return</span> msg;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">writeTF</span><span class="params">(String msg)</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;tf card write a msg : &quot;</span> + msg);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//定义适配器类（SD兼容TF）</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">SDAdapterTF</span> <span class="keyword">extends</span> <span class="title class_">TFCardImpl</span> <span class="keyword">implements</span> <span class="title class_">SDCard</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">readSD</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;adapter read tf card &quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> readTF();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">writeSD</span><span class="params">(String msg)</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;adapter write tf card&quot;</span>);</span><br><span class="line">        writeTF(msg);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//测试类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Client</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">Computer</span> <span class="variable">computer</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Computer</span>();</span><br><span class="line">        <span class="type">SDCard</span> <span class="variable">sdCard</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">SDCardImpl</span>();</span><br><span class="line">        System.out.println(computer.readSD(sdCard));</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;------------&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="type">SDAdapterTF</span> <span class="variable">adapter</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">SDAdapterTF</span>();</span><br><span class="line">        System.out.println(computer.readSD(adapter));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>类适配器模式违背了合成复用原则。类适配器是客户类有一个接口规范的情况下可用，反之不可用。</p>
<h3 id="524-对象适配器模式"><a class="markdownIt-Anchor" href="#524-对象适配器模式">#</a> 5.2.4 对象适配器模式</h3>
<p>实现方式：对象适配器模式可釆用将现有组件库中已经实现的组件引入适配器类中，该类同时实现当前系统的业务接口。</p>
<p>【例】读卡器</p>
<p>我们使用对象适配器模式将读卡器的案例进行改写。类图如下：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420230923369.png"
                      alt="在这里插入图片描述"
                ></p>
<p>代码如下：</p>
<p>类适配器模式的代码，我们只需要修改适配器类（SDAdapterTF）和测试类。</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//创建适配器对象（SD兼容TF）</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">SDAdapterTF</span>  <span class="keyword">implements</span> <span class="title class_">SDCard</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> TFCard tfCard;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">SDAdapterTF</span><span class="params">(TFCard tfCard)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.tfCard = tfCard;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">readSD</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;adapter read tf card &quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> tfCard.readTF();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">writeSD</span><span class="params">(String msg)</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;adapter write tf card&quot;</span>);</span><br><span class="line">        tfCard.writeTF(msg);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//测试类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Client</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">Computer</span> <span class="variable">computer</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Computer</span>();</span><br><span class="line">        <span class="type">SDCard</span> <span class="variable">sdCard</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">SDCardImpl</span>();</span><br><span class="line">        System.out.println(computer.readSD(sdCard));</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;------------&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="type">TFCard</span> <span class="variable">tfCard</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">TFCardImpl</span>();</span><br><span class="line">        <span class="type">SDAdapterTF</span> <span class="variable">adapter</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">SDAdapterTF</span>(tfCard);</span><br><span class="line">        System.out.println(computer.readSD(adapter));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<blockquote>
<p>注意：还有一个适配器模式是接口适配器模式。当不希望实现一个接口中所有的方法时，可以创建一个抽象类 Adapter ，实现所有方法。而此时我们只需要继承该抽象类即可。</p>
</blockquote>
<h3 id="525-应用场景"><a class="markdownIt-Anchor" href="#525-应用场景">#</a> 5.2.5 应用场景</h3>
<ul>
<li>以前开发的系统存在满足新系统功能需求的类，但其接口同新系统的接口不一致。</li>
<li>使用第三方提供的组件，但组件接口定义和自己要求的接口定义不同。</li>
</ul>
<h3 id="526-jdk源码解析"><a class="markdownIt-Anchor" href="#526-jdk源码解析">#</a> 5.2.6 JDK 源码解析</h3>
<p>Reader（字符流）、InputStream（字节流）的适配使用的是 InputStreamReader。</p>
<p>InputStreamReader 继承自 java.io 包中的 Reader，对他中的抽象的未实现的方法给出实现。如：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="type">int</span> <span class="title function_">read</span><span class="params">()</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">    <span class="keyword">return</span> sd.read();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="type">int</span> <span class="title function_">read</span><span class="params">(<span class="type">char</span> cbuf[], <span class="type">int</span> offset, <span class="type">int</span> length)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">    <span class="keyword">return</span> sd.read(cbuf, offset, length);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>如上代码中的 sd（StreamDecoder 类对象），在 Sun 的 JDK 实现中，实际的方法实现是对 sun.nio.cs.StreamDecoder 类的同名方法的调用封装。类结构图如下：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/2021042022553241.png"
                      alt="在这里插入图片描述"
                ></p>
<p>从上图可以看出：</p>
<ul>
<li>InputStreamReader 是对同样实现了 Reader 的 StreamDecoder 的封装。</li>
<li>StreamDecoder 不是 Java SE API 中的内容，是 Sun  JDK 给出的自身实现。但我们知道他们对构造方法中的字节流类（InputStream）进行封装，并通过该类进行了字节流和字符流之间的解码转换。</li>
</ul>
<p><font color="red">结论：</font></p>
<pre><code>从表层来看，InputStreamReader做了InputStream字节流类到Reader字符流之间的转换。而从如上Sun JDK中的实现类关系结构中可以看出，是StreamDecoder的设计实现在实际上采用了适配器模式。
</code></pre>
<h2 id="53-装饰者模式"><a class="markdownIt-Anchor" href="#53-装饰者模式">#</a> 5.3 装饰者模式</h2>
<h3 id="531-概述"><a class="markdownIt-Anchor" href="#531-概述">#</a> 5.3.1 概述</h3>
<p>我们先来看一个快餐店的例子。</p>
<p>快餐店有炒面、炒饭这些快餐，可以额外附加鸡蛋、火腿、培根这些配菜，当然加配菜需要额外加钱，每个配菜的价钱通常不太一样，那么计算总价就会显得比较麻烦。</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420231045990.png"
                      alt="在这里插入图片描述"
                ></p>
<p>使用继承的方式存在的问题：</p>
<ul>
<li>
<p>扩展性不好</p>
<p>如果要再加一种配料（火腿肠），我们就会发现需要给 FriedRice 和 FriedNoodles 分别定义一个子类。如果要新增一个快餐品类（炒河粉）的话，就需要定义更多的子类。</p>
</li>
<li>
<p>产生过多的子类</p>
</li>
</ul>
<p><strong>定义：</strong></p>
<pre><code>指在不改变现有对象结构的情况下，动态地给该对象增加一些职责（即增加其额外功能）的模式。
</code></pre>
<h3 id="532-结构"><a class="markdownIt-Anchor" href="#532-结构">#</a> 5.3.2 结构</h3>
<p>装饰（Decorator）模式中的角色：</p>
<ul>
<li>抽象构件（Component）角色 ：定义一个抽象接口以规范准备接收附加责任的对象。</li>
<li>具体构件（Concrete  Component）角色 ：实现抽象构件，通过装饰角色为其添加一些职责。</li>
<li>抽象装饰（Decorator）角色 ： 继承或实现抽象构件，并包含具体构件的实例，可以通过其子类扩展具体构件的功能。</li>
<li>具体装饰（ConcreteDecorator）角色 ：实现抽象装饰的相关方法，并给具体构件对象添加附加的责任。</li>
</ul>
<h3 id="533-案例"><a class="markdownIt-Anchor" href="#533-案例">#</a> 5.3.3 案例</h3>
<p>我们使用装饰者模式对快餐店案例进行改进，体会装饰者模式的精髓。</p>
<p>类图如下：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420231123895.png"
                      alt="在这里插入图片描述"
                ></p>
<p>代码如下：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//快餐接口</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title class_">FastFood</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">float</span> price;</span><br><span class="line">    <span class="keyword">private</span> String desc;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">FastFood</span><span class="params">()</span> &#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">FastFood</span><span class="params">(<span class="type">float</span> price, String desc)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.price = price;</span><br><span class="line">        <span class="built_in">this</span>.desc = desc;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setPrice</span><span class="params">(<span class="type">float</span> price)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.price = price;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="type">float</span> <span class="title function_">getPrice</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> price;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getDesc</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> desc;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setDesc</span><span class="params">(String desc)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.desc = desc;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">abstract</span> <span class="type">float</span> <span class="title function_">cost</span><span class="params">()</span>;  <span class="comment">//获取价格</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//炒饭</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">FriedRice</span> <span class="keyword">extends</span> <span class="title class_">FastFood</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">FriedRice</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="built_in">super</span>(<span class="number">10</span>, <span class="string">&quot;炒饭&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="type">float</span> <span class="title function_">cost</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> getPrice();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//炒面</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">FriedNoodles</span> <span class="keyword">extends</span> <span class="title class_">FastFood</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">FriedNoodles</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="built_in">super</span>(<span class="number">12</span>, <span class="string">&quot;炒面&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="type">float</span> <span class="title function_">cost</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> getPrice();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//配料类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title class_">Garnish</span> <span class="keyword">extends</span> <span class="title class_">FastFood</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> FastFood fastFood;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> FastFood <span class="title function_">getFastFood</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> fastFood;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setFastFood</span><span class="params">(FastFood fastFood)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.fastFood = fastFood;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Garnish</span><span class="params">(FastFood fastFood, <span class="type">float</span> price, String desc)</span> &#123;</span><br><span class="line">        <span class="built_in">super</span>(price,desc);</span><br><span class="line">        <span class="built_in">this</span>.fastFood = fastFood;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//鸡蛋配料</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Egg</span> <span class="keyword">extends</span> <span class="title class_">Garnish</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Egg</span><span class="params">(FastFood fastFood)</span> &#123;</span><br><span class="line">        <span class="built_in">super</span>(fastFood,<span class="number">1</span>,<span class="string">&quot;鸡蛋&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="type">float</span> <span class="title function_">cost</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> getPrice() + getFastFood().getPrice();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getDesc</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">super</span>.getDesc() + getFastFood().getDesc();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//培根配料</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Bacon</span> <span class="keyword">extends</span> <span class="title class_">Garnish</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Bacon</span><span class="params">(FastFood fastFood)</span> &#123;</span><br><span class="line"></span><br><span class="line">        <span class="built_in">super</span>(fastFood,<span class="number">2</span>,<span class="string">&quot;培根&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="type">float</span> <span class="title function_">cost</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> getPrice() + getFastFood().getPrice();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getDesc</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">super</span>.getDesc() + getFastFood().getDesc();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//测试类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Client</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="comment">//点一份炒饭</span></span><br><span class="line">        <span class="type">FastFood</span> <span class="variable">food</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">FriedRice</span>();</span><br><span class="line">        <span class="comment">//花费的价格</span></span><br><span class="line">        System.out.println(food.getDesc() + <span class="string">&quot; &quot;</span> + food.cost() + <span class="string">&quot;元&quot;</span>);</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;========&quot;</span>);</span><br><span class="line">        <span class="comment">//点一份加鸡蛋的炒饭</span></span><br><span class="line">        <span class="type">FastFood</span> <span class="variable">food1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">FriedRice</span>();</span><br><span class="line"></span><br><span class="line">        food1 = <span class="keyword">new</span> <span class="title class_">Egg</span>(food1);</span><br><span class="line">        <span class="comment">//花费的价格</span></span><br><span class="line">        System.out.println(food1.getDesc() + <span class="string">&quot; &quot;</span> + food1.cost() + <span class="string">&quot;元&quot;</span>);</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;========&quot;</span>);</span><br><span class="line">        <span class="comment">//点一份加培根的炒面</span></span><br><span class="line">        <span class="type">FastFood</span> <span class="variable">food2</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">FriedNoodles</span>();</span><br><span class="line">        food2 = <span class="keyword">new</span> <span class="title class_">Bacon</span>(food2);</span><br><span class="line">        <span class="comment">//花费的价格</span></span><br><span class="line">        System.out.println(food2.getDesc() + <span class="string">&quot; &quot;</span> + food2.cost() + <span class="string">&quot;元&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><strong>好处：</strong></p>
<ul>
<li>
<p>饰者模式可以带来比继承更加灵活性的扩展功能，使用更加方便，可以通过组合不同的装饰者对象来获取具有不同行为状态的多样化的结果。装饰者模式比继承更具良好的扩展性，完美的遵循开闭原则，继承是静态的附加责任，装饰者则是动态的附加责任。</p>
</li>
<li>
<p>装饰类和被装饰类可以独立发展，不会相互耦合，装饰模式是继承的一个替代模式，装饰模式可以动态扩展一个实现类的功能。</p>
</li>
</ul>
<h3 id="534-使用场景"><a class="markdownIt-Anchor" href="#534-使用场景">#</a> 5.3.4 使用场景</h3>
<ul>
<li>
<p>当不能采用继承的方式对系统进行扩充或者采用继承不利于系统扩展和维护时。</p>
<p>不能采用继承的情况主要有两类：</p>
<ul>
<li>第一类是系统中存在大量独立的扩展，为支持每一种组合将产生大量的子类，使得子类数目呈爆炸性增长；</li>
<li>第二类是因为类定义不能继承（如 final 类）</li>
</ul>
</li>
<li>
<p>在不影响其他对象的情况下，以动态、透明的方式给单个对象添加职责。</p>
</li>
<li>
<p>当对象的功能要求可以动态地添加，也可以再动态地撤销时。</p>
</li>
</ul>
<h3 id="535-jdk源码解析"><a class="markdownIt-Anchor" href="#535-jdk源码解析">#</a> 5.3.5 JDK 源码解析</h3>
<p>IO 流中的包装类使用到了装饰者模式。BufferedInputStream，BufferedOutputStream，BufferedReader，BufferedWriter。</p>
<p>我们以 BufferedWriter 举例来说明，先看看如何使用 BufferedWriter</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Demo</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception&#123;</span><br><span class="line">        <span class="comment">//创建BufferedWriter对象</span></span><br><span class="line">        <span class="comment">//创建FileWriter对象</span></span><br><span class="line">        <span class="type">FileWriter</span> <span class="variable">fw</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">FileWriter</span>(<span class="string">&quot;C:\\Users\\Think\\Desktop\\a.txt&quot;</span>);</span><br><span class="line">        <span class="type">BufferedWriter</span> <span class="variable">bw</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">BufferedWriter</span>(fw);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//写数据</span></span><br><span class="line">        bw.write(<span class="string">&quot;hello Buffered&quot;</span>);</span><br><span class="line"></span><br><span class="line">        bw.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>使用起来感觉确实像是装饰者模式，接下来看它们的结构：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420231153608.png"
                      alt="在这里插入图片描述"
                ></p>
<blockquote>
<p><font color="red">小结：</font></p>
<p>BufferedWriter 使用装饰者模式对 Writer 子实现类进行了增强，添加了缓冲区，提高了写数据的效率。</p>
</blockquote>
<h3 id="536-代理和装饰者的区别"><a class="markdownIt-Anchor" href="#536-代理和装饰者的区别">#</a> 5.3.6 代理和装饰者的区别</h3>
<p>静态代理和装饰者模式的区别：</p>
<ul>
<li>相同点：
<ul>
<li>都要实现与目标类相同的业务接口</li>
<li>在两个类中都要声明目标对象</li>
<li>都可以在不修改目标类的前提下增强目标方法</li>
</ul>
</li>
<li>不同点：
<ul>
<li>目的不同<br>
装饰者是为了增强目标对象<br>
静态代理是为了保护和隐藏目标对象</li>
<li>获取目标对象构建的地方不同<br>
装饰者是由外界传递进来，可以通过构造方法传递<br>
静态代理是在代理类内部创建，以此来隐藏目标对象</li>
</ul>
</li>
</ul>
<h2 id="54-桥接模式"><a class="markdownIt-Anchor" href="#54-桥接模式">#</a> 5.4 桥接模式</h2>
<h3 id="541-概述"><a class="markdownIt-Anchor" href="#541-概述">#</a> 5.4.1 概述</h3>
<p>现在有一个需求，需要创建不同的图形，并且每个图形都有可能会有不同的颜色。我们可以利用继承的方式来设计类的关系：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/2021042022555665.png"
                      alt="在这里插入图片描述"
                ></p>
<p>我们可以发现有很多的类，假如我们再增加一个形状或再增加一种颜色，就需要创建更多的类。</p>
<p>试想，在一个有多种可能会变化的维度的系统中，用继承方式会造成类爆炸，扩展起来不灵活。每次在一个维度上新增一个具体实现都要增加多个子类。为了更加灵活的设计系统，我们此时可以考虑使用桥接模式。</p>
<p><strong>定义：</strong></p>
<pre><code>将抽象与实现分离，使它们可以独立变化。它是用组合关系代替继承关系来实现，从而降低了抽象和实现这两个可变维度的耦合度。
</code></pre>
<h3 id="542-结构"><a class="markdownIt-Anchor" href="#542-结构">#</a> 5.4.2 结构</h3>
<p>桥接（Bridge）模式包含以下主要角色：</p>
<ul>
<li>抽象化（Abstraction）角色 ：定义抽象类，并包含一个对实现化对象的引用。</li>
<li>扩展抽象化（Refined  Abstraction）角色 ：是抽象化角色的子类，实现父类中的业务方法，并通过组合关系调用实现化角色中的业务方法。</li>
<li>实现化（Implementor）角色 ：定义实现化角色的接口，供扩展抽象化角色调用。</li>
<li>具体实现化（Concrete Implementor）角色 ：给出实现化角色接口的具体实现。</li>
</ul>
<h3 id="543-案例"><a class="markdownIt-Anchor" href="#543-案例">#</a> 5.4.3 案例</h3>
<p>【例】视频播放器</p>
<p>需要开发一个跨平台视频播放器，可以在不同操作系统平台（如 Windows、Mac、Linux 等）上播放多种格式的视频文件，常见的视频格式包括 RMVB、AVI、WMV 等。该播放器包含了两个维度，适合使用桥接模式。</p>
<p>类图如下：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420231232717.png"
                      alt="在这里插入图片描述"
                ></p>
<p>代码如下：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//视频文件</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">VideoFile</span> &#123;</span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">decode</span><span class="params">(String fileName)</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//avi文件</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">AVIFile</span> <span class="keyword">implements</span> <span class="title class_">VideoFile</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">decode</span><span class="params">(String fileName)</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;avi视频文件：&quot;</span>+ fileName);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//rmvb文件</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">REVBBFile</span> <span class="keyword">implements</span> <span class="title class_">VideoFile</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">decode</span><span class="params">(String fileName)</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;rmvb文件：&quot;</span> + fileName);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//操作系统版本</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title class_">OperatingSystemVersion</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">protected</span> VideoFile videoFile;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">OperatingSystemVersion</span><span class="params">(VideoFile videoFile)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.videoFile = videoFile;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title function_">play</span><span class="params">(String fileName)</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//Windows版本</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Windows</span> <span class="keyword">extends</span> <span class="title class_">OperatingSystem</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Windows</span><span class="params">(VideoFile videoFile)</span> &#123;</span><br><span class="line">        <span class="built_in">super</span>(videoFile);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">play</span><span class="params">(String fileName)</span> &#123;</span><br><span class="line">        videoFile.decode(fileName);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//mac版本</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Mac</span> <span class="keyword">extends</span> <span class="title class_">OperatingSystemVersion</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Mac</span><span class="params">(VideoFile videoFile)</span> &#123;</span><br><span class="line">        <span class="built_in">super</span>(videoFile);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">play</span><span class="params">(String fileName)</span> &#123;</span><br><span class="line">		videoFile.decode(fileName);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//测试类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Client</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">OperatingSystem</span> <span class="variable">os</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Windows</span>(<span class="keyword">new</span> <span class="title class_">AVIFile</span>());</span><br><span class="line">        os.play(<span class="string">&quot;战狼3&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><strong>好处：</strong></p>
<ul>
<li>
<p>桥接模式提高了系统的可扩充性，在两个变化维度中任意扩展一个维度，都不需要修改原有系统。</p>
<p>如：如果现在还有一种视频文件类型 wmv，我们只需要再定义一个类实现 VideoFile 接口即可，其他类不需要发生变化。</p>
</li>
<li>
<p>实现细节对客户透明</p>
</li>
</ul>
<h3 id="544-使用场景"><a class="markdownIt-Anchor" href="#544-使用场景">#</a> 5.4.4 使用场景</h3>
<ul>
<li>当一个类存在两个独立变化的维度，且这两个维度都需要进行扩展时。</li>
<li>当一个系统不希望使用继承或因为多层次继承导致系统类的个数急剧增加时。</li>
<li>当一个系统需要在构件的抽象化角色和具体化角色之间增加更多的灵活性时。避免在两个层次之间建立静态的继承联系，通过桥接模式可以使它们在抽象层建立一个关联关系。</li>
</ul>
<h2 id="55-外观模式"><a class="markdownIt-Anchor" href="#55-外观模式">#</a> 5.5 外观模式</h2>
<h3 id="551-概述"><a class="markdownIt-Anchor" href="#551-概述">#</a> 5.5.1 概述</h3>
<p>有些人可能炒过股票，但其实大部分人都不太懂，这种没有足够了解证券知识的情况下做股票是很容易亏钱的，刚开始炒股肯定都会想，如果有个懂行的帮帮手就好，其实基金就是个好帮手，支付宝里就有许多的基金，它将投资者分散的资金集中起来，交由专业的经理人进行管理，投资于股票、债券、外汇等领域，而基金投资的收益归持有者所有，管理机构收取一定比例的托管管理费用。</p>
<p><strong>定义：</strong></p>
<pre><code>又名门面模式，是一种通过为多个复杂的子系统提供一个一致的接口，而使这些子系统更加容易被访问的模式。该模式对外有一个统一接口，外部应用程序不用关心内部子系统的具体的细节，这样会大大降低应用程序的复杂度，提高了程序的可维护性。

外观（Facade）模式是“迪米特法则”的典型应用
</code></pre>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420225633681.png"
                      alt="在这里插入图片描述"
                ></p>
<h3 id="552-结构"><a class="markdownIt-Anchor" href="#552-结构">#</a> 5.5.2 结构</h3>
<p>外观（Facade）模式包含以下主要角色：</p>
<ul>
<li>外观（Facade）角色：为多个子系统对外提供一个共同的接口。</li>
<li>子系统（Sub System）角色：实现系统的部分功能，客户可以通过外观角色访问它。</li>
</ul>
<h3 id="553-案例"><a class="markdownIt-Anchor" href="#553-案例">#</a> 5.5.3 案例</h3>
<p>【例】智能家电控制</p>
<p>小明的爷爷已经 60 岁了，一个人在家生活：每次都需要打开灯、打开电视、打开空调；睡觉时关闭灯、关闭电视、关闭空调；操作起来都比较麻烦。所以小明给爷爷买了智能音箱，可以通过语音直接控制这些智能家电的开启和关闭。类图如下：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420231302277.png"
                      alt="在这里插入图片描述"
                ></p>
<p>代码如下：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//灯类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Light</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">on</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;打开了灯....&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">off</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;关闭了灯....&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//电视类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TV</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">on</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;打开了电视....&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">off</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;关闭了电视....&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//控制类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">AirCondition</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">on</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;打开了空调....&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">off</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;关闭了空调....&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//智能音箱</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">SmartAppliancesFacade</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Light light;</span><br><span class="line">    <span class="keyword">private</span> TV tv;</span><br><span class="line">    <span class="keyword">private</span> AirCondition airCondition;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">SmartAppliancesFacade</span><span class="params">()</span> &#123;</span><br><span class="line">        light = <span class="keyword">new</span> <span class="title class_">Light</span>();</span><br><span class="line">        tv = <span class="keyword">new</span> <span class="title class_">TV</span>();</span><br><span class="line">        airCondition = <span class="keyword">new</span> <span class="title class_">AirCondition</span>();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">say</span><span class="params">(String message)</span> &#123;</span><br><span class="line">        <span class="keyword">if</span>(message.contains(<span class="string">&quot;打开&quot;</span>)) &#123;</span><br><span class="line">            on();</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span>(message.contains(<span class="string">&quot;关闭&quot;</span>)) &#123;</span><br><span class="line">            off();</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;我还听不懂你说的！！！&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//起床后一键开电器</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">void</span> <span class="title function_">on</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;起床了&quot;</span>);</span><br><span class="line">        light.on();</span><br><span class="line">        tv.on();</span><br><span class="line">        airCondition.on();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//睡觉一键关电器</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">void</span> <span class="title function_">off</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;睡觉了&quot;</span>);</span><br><span class="line">        light.off();</span><br><span class="line">        tv.off();</span><br><span class="line">        airCondition.off();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//测试类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Client</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="comment">//创建外观对象</span></span><br><span class="line">        <span class="type">SmartAppliancesFacade</span> <span class="variable">facade</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">SmartAppliancesFacade</span>();</span><br><span class="line">        <span class="comment">//客户端直接与外观对象进行交互</span></span><br><span class="line">        facade.say(<span class="string">&quot;打开家电&quot;</span>);</span><br><span class="line">        facade.say(<span class="string">&quot;关闭家电&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><strong>好处：</strong></p>
<ul>
<li>降低了子系统与客户端之间的耦合度，使得子系统的变化不会影响调用它的客户类。</li>
<li>对客户屏蔽了子系统组件，减少了客户处理的对象数目，并使得子系统使用起来更加容易。</li>
</ul>
<p><strong>缺点：</strong></p>
<ul>
<li>不符合开闭原则，修改很麻烦</li>
</ul>
<h3 id="554-使用场景"><a class="markdownIt-Anchor" href="#554-使用场景">#</a> 5.5.4 使用场景</h3>
<ul>
<li>对分层结构系统构建时，使用外观模式定义子系统中每层的入口点可以简化子系统之间的依赖关系。</li>
<li>当一个复杂系统的子系统很多时，外观模式可以为系统设计一个简单的接口供外界访问。</li>
<li>当客户端与多个子系统之间存在很大的联系时，引入外观模式可将它们分离，从而提高子系统的独立性和可移植性。</li>
</ul>
<h3 id="555-源码解析"><a class="markdownIt-Anchor" href="#555-源码解析">#</a> 5.5.5 源码解析</h3>
<p>使用 tomcat 作为 web 容器时，接收浏览器发送过来的请求，tomcat 会将请求信息封装成 ServletRequest 对象，如下图①处对象。但是大家想想 ServletRequest 是一个接口，它还有一个子接口 HttpServletRequest，而我们知道该 request 对象肯定是一个 HttpServletRequest 对象的子实现类对象，到底是哪个类的对象呢？可以通过输出 request 对象，我们就会发现是一个名为 RequestFacade 的类的对象。</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420231358807.png"
                      alt="在这里插入图片描述"
                ></p>
<p>RequestFacade 类就使用了外观模式。先看结构图：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420231425763.png"
                      alt="在这里插入图片描述"
                ></p>
<p><strong>为什么在此处使用外观模式呢？</strong></p>
<pre><code>定义 RequestFacade 类，分别实现 ServletRequest ，同时定义私有成员变量 Request ，并且方法的实现调用 Request  的实现。然后，将 RequestFacade上转为 ServletRequest  传给 servlet 的 service 方法，这样即使在 servlet 中被下转为 RequestFacade ，也不能访问私有成员变量对象中的方法。既用了 Request ，又能防止其中方法被不合理的访问。
</code></pre>
<h2 id="56-组合模式"><a class="markdownIt-Anchor" href="#56-组合模式">#</a> 5.6 组合模式</h2>
<h3 id="561-概述"><a class="markdownIt-Anchor" href="#561-概述">#</a> 5.6.1 概述</h3>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420225707204.png"
                      alt="在这里插入图片描述"
                ></p>
<pre><code>对于这个图片肯定会非常熟悉，上图我们可以看做是一个文件系统，对于这样的结构我们称之为树形结构。在树形结构中可以通过调用某个方法来遍历整个树，当我们找到某个叶子节点后，就可以对叶子节点进行相关的操作。可以将这颗树理解成一个大的容器，容器里面包含很多的成员对象，这些成员对象即可是容器对象也可以是叶子对象。但是由于容器对象和叶子对象在功能上面的区别，使得我们在使用的过程中必须要区分容器对象和叶子对象，但是这样就会给客户带来不必要的麻烦，作为客户而已，它始终希望能够一致的对待容器对象和叶子对象。
</code></pre>
<p><strong>定义：</strong></p>
<pre><code>又名部分整体模式，是用于把一组相似的对象当作一个单一的对象。组合模式依据树形结构来组合对象，用来表示部分以及整体层次。这种类型的设计模式属于结构型模式，它创建了对象组的树形结构。
</code></pre>
<h3 id="562-结构"><a class="markdownIt-Anchor" href="#562-结构">#</a> 5.6.2 结构</h3>
<p>组合模式主要包含三种角色：</p>
<ul>
<li>抽象根节点（Component）：定义系统各层次对象的共有方法和属性，可以预先定义一些默认行为和属性。</li>
<li>树枝节点（Composite）：定义树枝节点的行为，存储子节点，组合树枝节点和叶子节点形成一个树形结构。</li>
<li>叶子节点（Leaf）：叶子节点对象，其下再无分支，是系统层次遍历的最小单位。</li>
</ul>
<h3 id="563-案例实现"><a class="markdownIt-Anchor" href="#563-案例实现">#</a> 5.6.3 案例实现</h3>
<p>【例】软件菜单</p>
<p>如下图，我们在访问别的一些管理系统时，经常可以看到类似的菜单。一个菜单可以包含菜单项（菜单项是指不再包含其他内容的菜单条目），也可以包含带有其他菜单项的菜单，因此使用组合模式描述菜单就很恰当，我们的需求是针对一个菜单，打印出其包含的所有菜单以及菜单项的名称。</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420231509643.png"
                      alt="在这里插入图片描述"
                ></p>
<p>要实现该案例，我们先画出类图：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420231525497.png"
                      alt="在这里插入图片描述"
                ></p>
<p><strong>代码实现：</strong></p>
<p>不管是菜单还是菜单项，都应该继承自统一的接口，这里姑且将这个统一的接口称为菜单组件。</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//菜单组件  不管是菜单还是菜单项，都应该继承该类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title class_">MenuComponent</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">protected</span> String name;</span><br><span class="line">    <span class="keyword">protected</span> <span class="type">int</span> level;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//添加菜单</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">add</span><span class="params">(MenuComponent menuComponent)</span>&#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">UnsupportedOperationException</span>();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//移除菜单</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">remove</span><span class="params">(MenuComponent menuComponent)</span>&#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">UnsupportedOperationException</span>();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//获取指定的子菜单</span></span><br><span class="line">    <span class="keyword">public</span> MenuComponent <span class="title function_">getChild</span><span class="params">(<span class="type">int</span> i)</span>&#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">UnsupportedOperationException</span>();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//获取菜单名称</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getName</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">print</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">UnsupportedOperationException</span>();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>这里的 MenuComponent 定义为抽象类，因为有一些共有的属性和行为要在该类中实现，Menu 和 MenuItem 类就可以只覆盖自己感兴趣的方法，而不用搭理不需要或者不感兴趣的方法，举例来说，Menu 类可以包含子菜单，因此需要覆盖 add ()、remove ()、getChild () 方法，但是 MenuItem 就不应该有这些方法。这里给出的默认实现是抛出异常，你也可以根据自己的需要改写默认实现。</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Menu</span> <span class="keyword">extends</span> <span class="title class_">MenuComponent</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> List&lt;MenuComponent&gt; menuComponentList;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Menu</span><span class="params">(String name,<span class="type">int</span> level)</span>&#123;</span><br><span class="line">        <span class="built_in">this</span>.level = level;</span><br><span class="line">        <span class="built_in">this</span>.name = name;</span><br><span class="line">        menuComponentList = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;MenuComponent&gt;();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">add</span><span class="params">(MenuComponent menuComponent)</span> &#123;</span><br><span class="line">        menuComponentList.add(menuComponent);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">remove</span><span class="params">(MenuComponent menuComponent)</span> &#123;</span><br><span class="line">        menuComponentList.remove(menuComponent);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> MenuComponent <span class="title function_">getChild</span><span class="params">(<span class="type">int</span> i)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> menuComponentList.get(i);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">print</span><span class="params">()</span> &#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">1</span>; i &lt; level; i++) &#123;</span><br><span class="line">            System.out.print(<span class="string">&quot;--&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(name);</span><br><span class="line">        <span class="keyword">for</span> (MenuComponent menuComponent : menuComponentList) &#123;</span><br><span class="line">            menuComponent.print();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>Menu 类已经实现了除了 getName 方法的其他所有方法，因为 Menu 类具有添加菜单，移除菜单和获取子菜单的功能。</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MenuItem</span> <span class="keyword">extends</span> <span class="title class_">MenuComponent</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">MenuItem</span><span class="params">(String name,<span class="type">int</span> level)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.name = name;</span><br><span class="line">        <span class="built_in">this</span>.level = level;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">print</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">1</span>; i &lt; level; i++) &#123;</span><br><span class="line">            System.out.print(<span class="string">&quot;--&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(name);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>MenuItem 是菜单项，不能再有子菜单，所以添加菜单，移除菜单和获取子菜单的功能并不能实现。</p>
<h3 id="564-组合模式的分类"><a class="markdownIt-Anchor" href="#564-组合模式的分类">#</a> 5.6.4 组合模式的分类</h3>
<p>在使用组合模式时，根据抽象构件类的定义形式，我们可将组合模式分为透明组合模式和安全组合模式两种形式。</p>
<ul>
<li>
<p>透明组合模式</p>
<p>透明组合模式中，抽象根节点角色中声明了所有用于管理成员对象的方法，比如在示例中  <code>MenuComponent</code>  声明了  <code>add</code> 、 <code>remove</code>  、 <code>getChild</code>  方法，这样做的好处是确保所有的构件类都有相同的接口。透明组合模式也是组合模式的标准形式。</p>
<p>透明组合模式的缺点是不够安全，因为叶子对象和容器对象在本质上是有区别的，叶子对象不可能有下一个层次的对象，即不可能包含成员对象，因此为其提供 add ()、remove () 等方法是没有意义的，这在编译阶段不会出错，但在运行阶段如果调用这些方法可能会出错（如果没有提供相应的错误处理代码）</p>
</li>
<li>
<p>安全组合模式</p>
<p>在安全组合模式中，在抽象构件角色中没有声明任何用于管理成员对象的方法，而是在树枝节点  <code>Menu</code>  类中声明并实现这些方法。安全组合模式的缺点是不够透明，因为叶子构件和容器构件具有不同的方法，且容器构件中那些用于管理成员对象的方法没有在抽象构件类中定义，因此客户端不能完全针对抽象编程，必须有区别地对待叶子构件和容器构件。</p>
</li>
</ul>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420231540386.png"
                      alt="在这里插入图片描述"
                ></p>
<h3 id="565-优点"><a class="markdownIt-Anchor" href="#565-优点">#</a> 5.6.5 优点</h3>
<ul>
<li>组合模式可以清楚地定义分层次的复杂对象，表示对象的全部或部分层次，它让客户端忽略了层次的差异，方便对整个层次结构进行控制。</li>
<li>客户端可以一致地使用一个组合结构或其中单个对象，不必关心处理的是单个对象还是整个组合结构，简化了客户端代码。</li>
<li>在组合模式中增加新的树枝节点和叶子节点都很方便，无须对现有类库进行任何修改，符合 “开闭原则”。</li>
<li>组合模式为树形结构的面向对象实现提供了一种灵活的解决方案，通过叶子节点和树枝节点的递归组合，可以形成复杂的树形结构，但对树形结构的控制却非常简单。</li>
</ul>
<h3 id="566-使用场景"><a class="markdownIt-Anchor" href="#566-使用场景">#</a> 5.6.6 使用场景</h3>
<p>组合模式正是应树形结构而生，所以组合模式的使用场景就是出现树形结构的地方。比如：文件目录显示，多级目录呈现等树形结构数据的操作。</p>
<h2 id="57-享元模式"><a class="markdownIt-Anchor" href="#57-享元模式">#</a> 5.7 享元模式</h2>
<h3 id="571-概述"><a class="markdownIt-Anchor" href="#571-概述">#</a> 5.7.1 概述</h3>
<p><strong>定义：</strong></p>
<pre><code>运用共享技术来有效地支持大量细粒度对象的复用。它通过共享已经存在的对象来大幅度减少需要创建的对象数量、避免大量相似对象的开销，从而提高系统资源的利用率。
</code></pre>
<h3 id="572-结构"><a class="markdownIt-Anchor" href="#572-结构">#</a> 5.7.2 结构</h3>
<p>享元（Flyweight ）模式中存在以下两种状态：</p>
<ol>
<li>内部状态，即不会随着环境的改变而改变的可共享部分。</li>
<li>外部状态，指随环境改变而改变的不可以共享的部分。享元模式的实现要领就是区分应用中的这两种状态，并将外部状态外部化。</li>
</ol>
<p>享元模式的主要有以下角色：</p>
<ul>
<li>抽象享元角色（Flyweight）：通常是一个接口或抽象类，在抽象享元类中声明了具体享元类公共的方法，这些方法可以向外界提供享元对象的内部数据（内部状态），同时也可以通过这些方法来设置外部数据（外部状态）。</li>
<li>具体享元（Concrete Flyweight）角色 ：它实现了抽象享元类，称为享元对象；在具体享元类中为内部状态提供了存储空间。通常我们可以结合单例模式来设计具体享元类，为每一个具体享元类提供唯一的享元对象。</li>
<li>非享元（Unsharable Flyweight) 角色 ：并不是所有的抽象享元类的子类都需要被共享，不能被共享的子类可设计为非共享具体享元类；当需要一个非共享具体享元类的对象时可以直接通过实例化创建。</li>
<li>享元工厂（Flyweight Factory）角色 ：负责创建和管理享元角色。当客户对象请求一个享元对象时，享元工厂检査系统中是否存在符合要求的享元对象，如果存在则提供给客户；如果不存在的话，则创建一个新的享元对象。</li>
</ul>
<h3 id="573-案例实现"><a class="markdownIt-Anchor" href="#573-案例实现">#</a> 5.7.3 案例实现</h3>
<p>【例】俄罗斯方块</p>
<p>下面的图片是众所周知的俄罗斯方块中的一个个方块，如果在俄罗斯方块这个游戏中，每个不同的方块都是一个实例对象，这些对象就要占用很多的内存空间，下面利用享元模式进行实现。</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420231600431.jpeg"
                      alt="在这里插入图片描述"
                ></p>
<p><strong>先来看类图：</strong></p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420231623551.png"
                      alt="在这里插入图片描述"
                ></p>
<p><strong>代码如下：</strong></p>
<p>俄罗斯方块有不同的形状，我们可以对这些形状向上抽取出 AbstractBox，用来定义共性的属性和行为。</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title class_">AbstractBox</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">abstract</span> String <span class="title function_">getShape</span><span class="params">()</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">display</span><span class="params">(String color)</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;方块形状：&quot;</span> + <span class="built_in">this</span>.getShape() + <span class="string">&quot; 颜色：&quot;</span> + color);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>接下来就是定义不同的形状了，IBox 类、LBox 类、OBox 类等。</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">IBox</span> <span class="keyword">extends</span> <span class="title class_">AbstractBox</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getShape</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;I&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">LBox</span> <span class="keyword">extends</span> <span class="title class_">AbstractBox</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getShape</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;L&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">OBox</span> <span class="keyword">extends</span> <span class="title class_">AbstractBox</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getShape</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;O&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>提供了一个工厂类（BoxFactory），用来管理享元对象（也就是 AbstractBox 子类对象），该工厂类对象只需要一个，所以可以使用单例模式。并给工厂类提供一个获取形状的方法。</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">BoxFactory</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> HashMap&lt;String, AbstractBox&gt; map;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="title function_">BoxFactory</span><span class="params">()</span> &#123;</span><br><span class="line">        map = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;String, AbstractBox&gt;();</span><br><span class="line">        <span class="type">AbstractBox</span> <span class="variable">iBox</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">IBox</span>();</span><br><span class="line">        <span class="type">AbstractBox</span> <span class="variable">lBox</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">LBox</span>();</span><br><span class="line">        <span class="type">AbstractBox</span> <span class="variable">oBox</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">OBox</span>();</span><br><span class="line">        map.put(<span class="string">&quot;I&quot;</span>, iBox);</span><br><span class="line">        map.put(<span class="string">&quot;L&quot;</span>, lBox);</span><br><span class="line">        map.put(<span class="string">&quot;O&quot;</span>, oBox);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> BoxFactory <span class="title function_">getInstance</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> SingletonHolder.INSTANCE;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">class</span> <span class="title class_">SingletonHolder</span> &#123;</span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">BoxFactory</span> <span class="variable">INSTANCE</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">BoxFactory</span>();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> AbstractBox <span class="title function_">getBox</span><span class="params">(String key)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> map.get(key);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<h3 id="575-优缺点和使用场景"><a class="markdownIt-Anchor" href="#575-优缺点和使用场景">#</a> 5.7.5 优缺点和使用场景</h3>
<p><strong>1，优点</strong></p>
<ul>
<li>极大减少内存中相似或相同对象数量，节约系统资源，提供系统性能</li>
<li>享元模式中的外部状态相对独立，且不影响内部状态</li>
</ul>
<p><strong>2，缺点：</strong></p>
<p>为了使对象可以共享，需要将享元对象的部分状态外部化，分离内部状态和外部状态，使程序逻辑复杂</p>
<p><strong>3，使用场景：</strong></p>
<ul>
<li>一个系统有大量相同或者相似的对象，造成内存的大量耗费。</li>
<li>对象的大部分状态都可以外部化，可以将这些外部状态传入对象中。</li>
<li>在使用享元模式时需要维护一个存储享元对象的享元池，而这需要耗费一定的系统资源，因此，应当在需要多次重复使用享元对象时才值得使用享元模式。</li>
</ul>
<h3 id="576-jdk源码解析"><a class="markdownIt-Anchor" href="#576-jdk源码解析">#</a> 5.7.6 JDK 源码解析</h3>
<p>Integer 类使用了享元模式。我们先看下面的例子：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Demo</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">Integer</span> <span class="variable">i1</span> <span class="operator">=</span> <span class="number">127</span>;</span><br><span class="line">        <span class="type">Integer</span> <span class="variable">i2</span> <span class="operator">=</span> <span class="number">127</span>;</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;i1和i2对象是否是同一个对象？&quot;</span> + (i1 == i2));</span><br><span class="line"></span><br><span class="line">        <span class="type">Integer</span> <span class="variable">i3</span> <span class="operator">=</span> <span class="number">128</span>;</span><br><span class="line">        <span class="type">Integer</span> <span class="variable">i4</span> <span class="operator">=</span> <span class="number">128</span>;</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;i3和i4对象是否是同一个对象？&quot;</span> + (i3 == i4));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>运行上面代码，结果如下：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420231644366.png"
                      alt="在这里插入图片描述"
                ></p>
<p>为什么第一个输出语句输出的是 true，第二个输出语句输出的是 false？通过反编译软件进行反编译，代码如下：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Demo</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">Integer</span> <span class="variable">i1</span> <span class="operator">=</span> Integer.valueOf((<span class="type">int</span>)<span class="number">127</span>);</span><br><span class="line">        Integer i2 Integer.valueOf((<span class="type">int</span>)<span class="number">127</span>);</span><br><span class="line">        System.out.println((String)<span class="keyword">new</span> <span class="title class_">StringBuilder</span>().append((String)<span class="string">&quot;i1\u548ci2\u5bf9\u8c61\u662f\u5426\u662f\u540c\u4e00\u4e2a\u5bf9\u8c61\uff1f&quot;</span>).append((<span class="type">boolean</span>)(i1 == i2)).toString());</span><br><span class="line">        <span class="type">Integer</span> <span class="variable">i3</span> <span class="operator">=</span> Integer.valueOf((<span class="type">int</span>)<span class="number">128</span>);</span><br><span class="line">        <span class="type">Integer</span> <span class="variable">i4</span> <span class="operator">=</span> Integer.valueOf((<span class="type">int</span>)<span class="number">128</span>);</span><br><span class="line">        System.out.println((String)<span class="keyword">new</span> <span class="title class_">StringBuilder</span>().append((String)<span class="string">&quot;i3\u548ci4\u5bf9\u8c61\u662f\u5426\u662f\u540c\u4e00\u4e2a\u5bf9\u8c61\uff1f&quot;</span>).append((<span class="type">boolean</span>)(i3 == i4)).toString());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>上面代码可以看到，直接给 Integer 类型的变量赋值基本数据类型数据的操作底层使用的是  <code>valueOf()</code>  ，所以只需要看该方法即可</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">class</span> <span class="title class_">Integer</span> <span class="keyword">extends</span> <span class="title class_">Number</span> <span class="keyword">implements</span> <span class="title class_">Comparable</span>&lt;Integer&gt; &#123;</span><br><span class="line">    </span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> Integer <span class="title function_">valueOf</span><span class="params">(<span class="type">int</span> i)</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (i &gt;= IntegerCache.low &amp;&amp; i &lt;= IntegerCache.high)</span><br><span class="line">            <span class="keyword">return</span> IntegerCache.cache[i + (-IntegerCache.low)];</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Integer</span>(i);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">class</span> <span class="title class_">IntegerCache</span> &#123;</span><br><span class="line">        <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">int</span> <span class="variable">low</span> <span class="operator">=</span> -<span class="number">128</span>;</span><br><span class="line">        <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">int</span> high;</span><br><span class="line">        <span class="keyword">static</span> <span class="keyword">final</span> Integer cache[];</span><br><span class="line"></span><br><span class="line">        <span class="keyword">static</span> &#123;</span><br><span class="line">            <span class="type">int</span> <span class="variable">h</span> <span class="operator">=</span> <span class="number">127</span>;</span><br><span class="line">            <span class="type">String</span> <span class="variable">integerCacheHighPropValue</span> <span class="operator">=</span></span><br><span class="line">                sun.misc.VM.getSavedProperty(<span class="string">&quot;java.lang.Integer.IntegerCache.high&quot;</span>);</span><br><span class="line">            <span class="keyword">if</span> (integerCacheHighPropValue != <span class="literal">null</span>) &#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    <span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> parseInt(integerCacheHighPropValue);</span><br><span class="line">                    i = Math.max(i, <span class="number">127</span>);</span><br><span class="line">                    <span class="comment">// Maximum array size is Integer.MAX_VALUE</span></span><br><span class="line">                    h = Math.min(i, Integer.MAX_VALUE - (-low) -<span class="number">1</span>);</span><br><span class="line">                &#125; <span class="keyword">catch</span>( NumberFormatException nfe) &#123;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            high = h;</span><br><span class="line">            cache = <span class="keyword">new</span> <span class="title class_">Integer</span>[(high - low) + <span class="number">1</span>];</span><br><span class="line">            <span class="type">int</span> <span class="variable">j</span> <span class="operator">=</span> low;</span><br><span class="line">            <span class="keyword">for</span>(<span class="type">int</span> <span class="variable">k</span> <span class="operator">=</span> <span class="number">0</span>; k &lt; cache.length; k++)</span><br><span class="line">                cache[k] = <span class="keyword">new</span> <span class="title class_">Integer</span>(j++);</span><br><span class="line">            <span class="comment">// range [-128, 127] must be interned (JLS7 5.1.7)</span></span><br><span class="line">            <span class="keyword">assert</span> IntegerCache.high &gt;= <span class="number">127</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">private</span> <span class="title function_">IntegerCache</span><span class="params">()</span> &#123;&#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>可以看到  <code>Integer</code>  默认先创建并缓存  <code>-128 ~ 127</code>  之间数的  <code>Integer</code>  对象，当调用  <code>valueOf</code>  时如果参数在  <code>-128 ~ 127</code>  之间则计算下标并从缓存中返回，否则创建一个新的  <code>Integer</code>  对象。</p>
<h1 id="6行为型模式"><a class="markdownIt-Anchor" href="#6行为型模式">#</a> 6，行为型模式</h1>
<p>行为型模式用于描述程序在运行时复杂的流程控制，即描述多个类或对象之间怎样相互协作共同完成单个对象都无法单独完成的任务，它涉及算法与对象间职责的分配。</p>
<p>行为型模式分为类行为模式和对象行为模式，前者采用继承机制来在类间分派行为，后者采用组合或聚合在对象间分配行为。由于组合关系或聚合关系比继承关系耦合度低，满足 “合成复用原则”，所以对象行为模式比类行为模式具有更大的灵活性。</p>
<p>行为型模式分为：</p>
<ol>
<li>模板方法模式</li>
<li>策略模式</li>
<li>命令模式</li>
<li>职责链模式</li>
<li>状态模式</li>
<li>观察者模式</li>
<li>中介者模式</li>
<li>迭代器模式</li>
<li>访问者模式</li>
<li>备忘录模式</li>
<li>解释器模式</li>
</ol>
<p>以上 11 种行为型模式，除了模板方法模式和解释器模式是类行为型模式，其他的全部属于对象行为型模式。</p>
<h2 id="61-模板方法模式"><a class="markdownIt-Anchor" href="#61-模板方法模式">#</a> 6.1 模板方法模式</h2>
<h3 id="611-概述"><a class="markdownIt-Anchor" href="#611-概述">#</a> 6.1.1 概述</h3>
<p>在面向对象程序设计过程中，程序员常常会遇到这种情况：设计一个系统时知道了算法所需的关键步骤，而且确定了这些步骤的执行顺序，但某些步骤的具体实现还未知，或者说某些步骤的实现与具体的环境相关。</p>
<p>例如，去银行办理业务一般要经过以下 4 个流程：取号、排队、办理具体业务、对银行工作人员进行评分等，其中取号、排队和对银行工作人员进行评分的业务对每个客户是一样的，可以在父类中实现，但是办理具体业务却因人而异，它可能是存款、取款或者转账等，可以延迟到子类中实现。</p>
<p><strong>定义：</strong></p>
<p>定义一个操作中的算法骨架，而将算法的一些步骤延迟到子类中，使得子类可以不改变该算法结构的情况下重定义该算法的某些特定步骤。</p>
<h3 id="612-结构"><a class="markdownIt-Anchor" href="#612-结构">#</a> 6.1.2 结构</h3>
<p>模板方法（Template Method）模式包含以下主要角色：</p>
<ul>
<li>
<p>抽象类（Abstract Class）：负责给出一个算法的轮廓和骨架。它由一个模板方法和若干个基本方法构成。</p>
<ul>
<li>
<p>模板方法：定义了算法的骨架，按某种顺序调用其包含的基本方法。</p>
</li>
<li>
<p>基本方法：是实现算法各个步骤的方法，是模板方法的组成部分。基本方法又可以分为三种：</p>
<ul>
<li>
<p>抽象方法 (Abstract Method) ：一个抽象方法由抽象类声明、由其具体子类实现。</p>
</li>
<li>
<p>具体方法 (Concrete Method) ：一个具体方法由一个抽象类或具体类声明并实现，其子类可以进行覆盖也可以直接继承。</p>
</li>
<li>
<p>钩子方法 (Hook Method) ：在抽象类中已经实现，包括用于判断的逻辑方法和需要子类重写的空方法两种。</p>
<p>一般钩子方法是用于判断的逻辑方法，这类方法名一般为 isXxx，返回值类型为 boolean 类型。</p>
</li>
</ul>
</li>
</ul>
</li>
<li>
<p>具体子类（Concrete Class）：实现抽象类中所定义的抽象方法和钩子方法，它们是一个顶级逻辑的组成步骤。</p>
</li>
</ul>
<h3 id="613-案例实现"><a class="markdownIt-Anchor" href="#613-案例实现">#</a> 6.1.3 案例实现</h3>
<p>【例】炒菜</p>
<p>炒菜的步骤是固定的，分为倒油、热油、倒蔬菜、倒调料品、翻炒等步骤。现通过模板方法模式来用代码模拟。类图如下：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420231706979.png"
                      alt="在这里插入图片描述"
                ></p>
<p>代码如下：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title class_">AbstractClass</span> &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title function_">cookProcess</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="comment">//第一步：倒油</span></span><br><span class="line">        <span class="built_in">this</span>.pourOil();</span><br><span class="line">        <span class="comment">//第二步：热油</span></span><br><span class="line">        <span class="built_in">this</span>.heatOil();</span><br><span class="line">        <span class="comment">//第三步：倒蔬菜</span></span><br><span class="line">        <span class="built_in">this</span>.pourVegetable();</span><br><span class="line">        <span class="comment">//第四步：倒调味料</span></span><br><span class="line">        <span class="built_in">this</span>.pourSauce();</span><br><span class="line">        <span class="comment">//第五步：翻炒</span></span><br><span class="line">        <span class="built_in">this</span>.fry();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">pourOil</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;倒油&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//第二步：热油是一样的，所以直接实现</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">heatOil</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;热油&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//第三步：倒蔬菜是不一样的（一个下包菜，一个是下菜心）</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title function_">pourVegetable</span><span class="params">()</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//第四步：倒调味料是不一样</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title function_">pourSauce</span><span class="params">()</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">//第五步：翻炒是一样的，所以直接实现</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">fry</span><span class="params">()</span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;炒啊炒啊炒到熟啊&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ConcreteClass_BaoCai</span> <span class="keyword">extends</span> <span class="title class_">AbstractClass</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">pourVegetable</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;下锅的蔬菜是包菜&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">pourSauce</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;下锅的酱料是辣椒&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ConcreteClass_CaiXin</span> <span class="keyword">extends</span> <span class="title class_">AbstractClass</span> &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">pourVegetable</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;下锅的蔬菜是菜心&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">pourSauce</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;下锅的酱料是蒜蓉&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Client</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="comment">//炒手撕包菜</span></span><br><span class="line">        <span class="type">ConcreteClass_BaoCai</span> <span class="variable">baoCai</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ConcreteClass_BaoCai</span>();</span><br><span class="line">        baoCai.cookProcess();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//炒蒜蓉菜心</span></span><br><span class="line">        <span class="type">ConcreteClass_CaiXin</span> <span class="variable">caiXin</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ConcreteClass_CaiXin</span>();</span><br><span class="line">        caiXin.cookProcess();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<blockquote>
<p>注意：为防止恶意操作，一般模板方法都加上 final 关键词。</p>
</blockquote>
<h3 id="613-优缺点"><a class="markdownIt-Anchor" href="#613-优缺点">#</a> 6.1.3 优缺点</h3>
<p><strong>优点：</strong></p>
<ul>
<li>
<p>提高代码复用性</p>
<p>将相同部分的代码放在抽象的父类中，而将不同的代码放入不同的子类中。</p>
</li>
<li>
<p>实现了反向控制</p>
<p>通过一个父类调用其子类的操作，通过对子类的具体实现扩展不同的行为，实现了反向控制 ，并符合 “开闭原则”。</p>
</li>
</ul>
<p><strong>缺点：</strong></p>
<ul>
<li>对每个不同的实现都需要定义一个子类，这会导致类的个数增加，系统更加庞大，设计也更加抽象。</li>
<li>父类中的抽象方法由子类实现，子类执行的结果会影响父类的结果，这导致一种反向的控制结构，它提高了代码阅读的难度。</li>
</ul>
<h3 id="614-适用场景"><a class="markdownIt-Anchor" href="#614-适用场景">#</a> 6.1.4 适用场景</h3>
<ul>
<li>算法的整体步骤很固定，但其中个别部分易变时，这时候可以使用模板方法模式，将容易变的部分抽象出来，供子类实现。</li>
<li>需要通过子类来决定父类算法中某个步骤是否执行，实现子类对父类的反向控制。</li>
</ul>
<h3 id="615-jdk源码解析"><a class="markdownIt-Anchor" href="#615-jdk源码解析">#</a> 6.1.5 JDK 源码解析</h3>
<p>InputStream 类就使用了模板方法模式。在 InputStream 类中定义了多个  <code>read()</code>  方法，如下：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title class_">InputStream</span> <span class="keyword">implements</span> <span class="title class_">Closeable</span> &#123;</span><br><span class="line">    <span class="comment">//抽象方法，要求子类必须重写</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">abstract</span> <span class="type">int</span> <span class="title function_">read</span><span class="params">()</span> <span class="keyword">throws</span> IOException;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">read</span><span class="params">(<span class="type">byte</span> b[])</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">        <span class="keyword">return</span> read(b, <span class="number">0</span>, b.length);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">read</span><span class="params">(<span class="type">byte</span> b[], <span class="type">int</span> off, <span class="type">int</span> len)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">        <span class="keyword">if</span> (b == <span class="literal">null</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">NullPointerException</span>();</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (off &lt; <span class="number">0</span> || len &lt; <span class="number">0</span> || len &gt; b.length - off) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">IndexOutOfBoundsException</span>();</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (len == <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="type">int</span> <span class="variable">c</span> <span class="operator">=</span> read(); <span class="comment">//调用了无参的read方法，该方法是每次读取一个字节数据</span></span><br><span class="line">        <span class="keyword">if</span> (c == -<span class="number">1</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        b[off] = (<span class="type">byte</span>)c;</span><br><span class="line"></span><br><span class="line">        <span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">for</span> (; i &lt; len ; i++) &#123;</span><br><span class="line">                c = read();</span><br><span class="line">                <span class="keyword">if</span> (c == -<span class="number">1</span>) &#123;</span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">                &#125;</span><br><span class="line">                b[off + i] = (<span class="type">byte</span>)c;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException ee) &#123;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> i;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>从上面代码可以看到，无参的  <code>read()</code>  方法是抽象方法，要求子类必须实现。而  <code>read(byte b[])</code>  方法调用了  <code>read(byte b[], int off, int len)</code>  方法，所以在此处重点看的方法是带三个参数的方法。</p>
<p>在该方法中第 18 行、27 行，可以看到调用了无参的抽象的  <code>read()</code>  方法。</p>
<p>总结如下： 在 InputStream 父类中已经定义好了读取一个字节数组数据的方法是每次读取一个字节，并将其存储到数组的第一个索引位置，读取 len 个字节数据。具体如何读取一个字节数据呢？由子类实现。</p>
<h2 id="62-策略模式"><a class="markdownIt-Anchor" href="#62-策略模式">#</a> 6.2 策略模式</h2>
<h3 id="621-概述"><a class="markdownIt-Anchor" href="#621-概述">#</a> 6.2.1 概述</h3>
<p>先看下面的图片，我们去旅游选择出行模式有很多种，可以骑自行车、可以坐汽车、可以坐火车、可以坐飞机。</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420231724170.png"
                      alt="在这里插入图片描述"
                ></p>
<p>作为一个程序猿，开发需要选择一款开发工具，当然可以进行代码开发的工具有很多，可以选择 Idea 进行开发，也可以使用 eclipse 进行开发，也可以使用其他的一些开发工具。</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420231753669.png"
                      alt="在这里插入图片描述"
                ></p>
<p><strong>定义：</strong></p>
<pre><code>该模式定义了一系列算法，并将每个算法封装起来，使它们可以相互替换，且算法的变化不会影响使用算法的客户。策略模式属于对象行为模式，它通过对算法进行封装，把使用算法的责任和算法的实现分割开来，并委派给不同的对象对这些算法进行管理。
</code></pre>
<h3 id="622-结构"><a class="markdownIt-Anchor" href="#622-结构">#</a> 6.2.2 结构</h3>
<p>策略模式的主要角色如下：</p>
<ul>
<li>抽象策略（Strategy）类：这是一个抽象角色，通常由一个接口或抽象类实现。此角色给出所有的具体策略类所需的接口。</li>
<li>具体策略（Concrete Strategy）类：实现了抽象策略定义的接口，提供具体的算法实现或行为。</li>
<li>环境（Context）类：持有一个策略类的引用，最终给客户端调用。</li>
</ul>
<h3 id="623-案例实现"><a class="markdownIt-Anchor" href="#623-案例实现">#</a> 6.2.3 案例实现</h3>
<p>【例】促销活动</p>
<p>一家百货公司在定年度的促销活动。针对不同的节日（春节、中秋节、圣诞节）推出不同的促销活动，由促销员将促销活动展示给客户。类图如下：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420231807973.png"
                      alt="在这里插入图片描述"
                ></p>
<p>代码如下：</p>
<p>定义百货公司所有促销活动的共同接口</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">Strategy</span> &#123;</span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">show</span><span class="params">()</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>定义具体策略角色（Concrete Strategy）：每个节日具体的促销活动</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//为春节准备的促销活动A</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">StrategyA</span> <span class="keyword">implements</span> <span class="title class_">Strategy</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">show</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;买一送一&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//为中秋准备的促销活动B</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">StrategyB</span> <span class="keyword">implements</span> <span class="title class_">Strategy</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">show</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;满200元减50元&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//为圣诞准备的促销活动C</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">StrategyC</span> <span class="keyword">implements</span> <span class="title class_">Strategy</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">show</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;满1000元加一元换购任意200元以下商品&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>定义环境角色（Context）：用于连接上下文，即把促销活动推销给客户，这里可以理解为销售员</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">SalesMan</span> &#123;                        </span><br><span class="line">    <span class="comment">//持有抽象策略角色的引用                              </span></span><br><span class="line">    <span class="keyword">private</span> Strategy strategy;                 </span><br><span class="line">                                               </span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">SalesMan</span><span class="params">(Strategy strategy)</span> &#123;       </span><br><span class="line">        <span class="built_in">this</span>.strategy = strategy;              </span><br><span class="line">    &#125;                                          </span><br><span class="line">                                               </span><br><span class="line">    <span class="comment">//向客户展示促销活动                                </span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">salesManShow</span><span class="params">()</span>&#123;                </span><br><span class="line">        strategy.show();                       </span><br><span class="line">    &#125;                                          </span><br><span class="line">&#125;                                              </span><br></pre></td></tr></table></figure></div>
<h3 id="624-优缺点"><a class="markdownIt-Anchor" href="#624-优缺点">#</a> 6.2.4 优缺点</h3>
<p><strong>1，优点：</strong></p>
<ul>
<li>
<p>策略类之间可以自由切换</p>
<p>由于策略类都实现同一个接口，所以使它们之间可以自由切换。</p>
</li>
<li>
<p>易于扩展</p>
<p>增加一个新的策略只需要添加一个具体的策略类即可，基本不需要改变原有的代码，符合 “开闭原则 “</p>
</li>
<li>
<p>避免使用多重条件选择语句（if else），充分体现面向对象设计思想。</p>
</li>
</ul>
<p><strong>2，缺点：</strong></p>
<ul>
<li>客户端必须知道所有的策略类，并自行决定使用哪一个策略类。</li>
<li>策略模式将造成产生很多策略类，可以通过使用享元模式在一定程度上减少对象的数量。</li>
</ul>
<h3 id="625-使用场景"><a class="markdownIt-Anchor" href="#625-使用场景">#</a> 6.2.5 使用场景</h3>
<ul>
<li>一个系统需要动态地在几种算法中选择一种时，可将每个算法封装到策略类中。</li>
<li>一个类定义了多种行为，并且这些行为在这个类的操作中以多个条件语句的形式出现，可将每个条件分支移入它们各自的策略类中以代替这些条件语句。</li>
<li>系统中各算法彼此完全独立，且要求对客户隐藏具体算法的实现细节时。</li>
<li>系统要求使用算法的客户不应该知道其操作的数据时，可使用策略模式来隐藏与算法相关的数据结构。</li>
<li>多个类只区别在表现行为不同，可以使用策略模式，在运行时动态选择具体要执行的行为。</li>
</ul>
<h3 id="626-jdk源码解析"><a class="markdownIt-Anchor" href="#626-jdk源码解析">#</a> 6.2.6 JDK 源码解析</h3>
<p><code>Comparator</code>  中的策略模式。在 Arrays 类中有一个  <code>sort()</code>  方法，如下：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Arrays</span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> &lt;T&gt; <span class="keyword">void</span> <span class="title function_">sort</span><span class="params">(T[] a, Comparator&lt;? <span class="built_in">super</span> T&gt; c)</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (c == <span class="literal">null</span>) &#123;</span><br><span class="line">            sort(a);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (LegacyMergeSort.userRequested)</span><br><span class="line">                legacyMergeSort(a, c);</span><br><span class="line">            <span class="keyword">else</span></span><br><span class="line">                TimSort.sort(a, <span class="number">0</span>, a.length, c, <span class="literal">null</span>, <span class="number">0</span>, <span class="number">0</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>Arrays 就是一个环境角色类，这个 sort 方法可以传一个新策略让 Arrays 根据这个策略来进行排序。就比如下面的测试类。</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">demo</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line"></span><br><span class="line">        Integer[] data = &#123;<span class="number">12</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">2</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">1</span>&#125;;</span><br><span class="line">        <span class="comment">// 实现降序排序</span></span><br><span class="line">        Arrays.sort(data, <span class="keyword">new</span> <span class="title class_">Comparator</span>&lt;Integer&gt;() &#123;</span><br><span class="line">            <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">compare</span><span class="params">(Integer o1, Integer o2)</span> &#123;</span><br><span class="line">                <span class="keyword">return</span> o2 - o1;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">        System.out.println(Arrays.toString(data)); <span class="comment">//[12, 5, 4, 3, 2, 2, 1]</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>这里我们在调用 Arrays 的 sort 方法时，第二个参数传递的是 Comparator 接口的子实现类对象。所以 Comparator 充当的是抽象策略角色，而具体的子实现类充当的是具体策略角色。环境角色类（Arrays）应该持有抽象策略的引用来调用。那么，Arrays 类的 sort 方法到底有没有使用 Comparator 子实现类中的  <code>compare()</code>  方法吗？让我们继续查看 TimSort 类的  <code>sort()</code>  方法，代码如下：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">TimSort</span>&lt;T&gt; &#123;</span><br><span class="line">    <span class="keyword">static</span> &lt;T&gt; <span class="keyword">void</span> <span class="title function_">sort</span><span class="params">(T[] a, <span class="type">int</span> lo, <span class="type">int</span> hi, Comparator&lt;? <span class="built_in">super</span> T&gt; c,</span></span><br><span class="line"><span class="params">                         T[] work, <span class="type">int</span> workBase, <span class="type">int</span> workLen)</span> &#123;</span><br><span class="line">        <span class="keyword">assert</span> c != <span class="literal">null</span> &amp;&amp; a != <span class="literal">null</span> &amp;&amp; lo &gt;= <span class="number">0</span> &amp;&amp; lo &lt;= hi &amp;&amp; hi &lt;= a.length;</span><br><span class="line"></span><br><span class="line">        <span class="type">int</span> <span class="variable">nRemaining</span>  <span class="operator">=</span> hi - lo;</span><br><span class="line">        <span class="keyword">if</span> (nRemaining &lt; <span class="number">2</span>)</span><br><span class="line">            <span class="keyword">return</span>;  <span class="comment">// Arrays of size 0 and 1 are always sorted</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// If array is small, do a &quot;mini-TimSort&quot; with no merges</span></span><br><span class="line">        <span class="keyword">if</span> (nRemaining &lt; MIN_MERGE) &#123;</span><br><span class="line">            <span class="type">int</span> <span class="variable">initRunLen</span> <span class="operator">=</span> countRunAndMakeAscending(a, lo, hi, c);</span><br><span class="line">            binarySort(a, lo, hi, lo + initRunLen, c);</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        ...</span><br><span class="line">    &#125;   </span><br><span class="line">        </span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> &lt;T&gt; <span class="type">int</span> <span class="title function_">countRunAndMakeAscending</span><span class="params">(T[] a, <span class="type">int</span> lo, <span class="type">int</span> hi,Comparator&lt;? <span class="built_in">super</span> T&gt; c)</span> &#123;</span><br><span class="line">        <span class="keyword">assert</span> lo &lt; hi;</span><br><span class="line">        <span class="type">int</span> <span class="variable">runHi</span> <span class="operator">=</span> lo + <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">if</span> (runHi == hi)</span><br><span class="line">            <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Find end of run, and reverse range if descending</span></span><br><span class="line">        <span class="keyword">if</span> (c.compare(a[runHi++], a[lo]) &lt; <span class="number">0</span>) &#123; <span class="comment">// Descending</span></span><br><span class="line">            <span class="keyword">while</span> (runHi &lt; hi &amp;&amp; c.compare(a[runHi], a[runHi - <span class="number">1</span>]) &lt; <span class="number">0</span>)</span><br><span class="line">                runHi++;</span><br><span class="line">            reverseRange(a, lo, runHi);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;                              <span class="comment">// Ascending</span></span><br><span class="line">            <span class="keyword">while</span> (runHi &lt; hi &amp;&amp; c.compare(a[runHi], a[runHi - <span class="number">1</span>]) &gt;= <span class="number">0</span>)</span><br><span class="line">                runHi++;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> runHi - lo;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>上面的代码中最终会跑到  <code>countRunAndMakeAscending()</code>  这个方法中。我们可以看见，只用了 compare 方法，所以在调用 Arrays.sort 方法只传具体 compare 重写方法的类对象就行，这也是 Comparator 接口中必须要子类实现的一个方法。</p>
<h2 id="63-命令模式"><a class="markdownIt-Anchor" href="#63-命令模式">#</a> 6.3 命令模式</h2>
<h3 id="631-概述"><a class="markdownIt-Anchor" href="#631-概述">#</a> 6.3.1 概述</h3>
<p>日常生活中，我们出去吃饭都会遇到下面的场景。<br>
<img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420231934811.png"
                      alt="在这里插入图片描述"
                ></p>
<p><strong>定义：</strong></p>
<p>将一个请求封装为一个对象，使发出请求的责任和执行请求的责任分割开。这样两者之间通过命令对象进行沟通，这样方便将命令对象进行存储、传递、调用、增加与管理。</p>
<h3 id="632-结构"><a class="markdownIt-Anchor" href="#632-结构">#</a> 6.3.2 结构</h3>
<p>命令模式包含以下主要角色：</p>
<ul>
<li>抽象命令类（Command）角色： 定义命令的接口，声明执行的方法。</li>
<li>具体命令（Concrete  Command）角色：具体的命令，实现命令接口；通常会持有接收者，并调用接收者的功能来完成命令要执行的操作。</li>
<li>实现者 / 接收者（Receiver）角色： 接收者，真正执行命令的对象。任何类都可能成为一个接收者，只要它能够实现命令要求实现的相应功能。</li>
<li>调用者 / 请求者（Invoker）角色： 要求命令对象执行请求，通常会持有命令对象，可以持有很多的命令对象。这个是客户端真正触发命令并要求命令执行相应操作的地方，也就是说相当于使用命令对象的入口。</li>
</ul>
<h3 id="633-案例实现"><a class="markdownIt-Anchor" href="#633-案例实现">#</a> 6.3.3 案例实现</h3>
<p>将上面的案例用代码实现，那我们就需要分析命令模式的角色在该案例中由谁来充当。</p>
<p>服务员： 就是调用者角色，由她来发起命令。</p>
<p>资深大厨： 就是接收者角色，真正命令执行的对象。</p>
<p>订单： 命令中包含订单。</p>
<p>类图如下：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420231954390.png"
                      alt="在这里插入图片描述"
                ></p>
<p>代码如下：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">Command</span> &#123;</span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">execute</span><span class="params">()</span>;<span class="comment">//只需要定义一个统一的执行方法</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">OrderCommand</span> <span class="keyword">implements</span> <span class="title class_">Command</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//持有接受者对象</span></span><br><span class="line">    <span class="keyword">private</span> SeniorChef receiver;</span><br><span class="line">    <span class="keyword">private</span> Order order;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">OrderCommand</span><span class="params">(SeniorChef receiver, Order order)</span>&#123;</span><br><span class="line">        <span class="built_in">this</span>.receiver = receiver;</span><br><span class="line">        <span class="built_in">this</span>.order = order;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">execute</span><span class="params">()</span>  &#123;</span><br><span class="line">        System.out.println(order.getDiningTable() + <span class="string">&quot;桌的订单：&quot;</span>);</span><br><span class="line">        Set&lt;String&gt; keys = order.getFoodDic().keySet();</span><br><span class="line">        <span class="keyword">for</span> (String key : keys) &#123;</span><br><span class="line">            receiver.makeFood(order.getFoodDic().get(key),key);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Thread.sleep(<span class="number">100</span>);<span class="comment">//停顿一下 模拟做饭的过程</span></span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        System.out.println(order.getDiningTable() + <span class="string">&quot;桌的饭弄好了&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Order</span> &#123;</span><br><span class="line">    <span class="comment">// 餐桌号码</span></span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> diningTable;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 用来存储餐名并记录份数</span></span><br><span class="line">    <span class="keyword">private</span> Map&lt;String, Integer&gt; foodDic = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;String, Integer&gt;();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">getDiningTable</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> diningTable;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setDiningTable</span><span class="params">(<span class="type">int</span> diningTable)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.diningTable = diningTable;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Map&lt;String, Integer&gt; <span class="title function_">getFoodDic</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> foodDic;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setFoodDic</span><span class="params">(String name, <span class="type">int</span> num)</span> &#123;</span><br><span class="line">        foodDic.put(name,num);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 资深大厨类 是命令的Receiver</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">SeniorChef</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">makeFood</span><span class="params">(<span class="type">int</span> num,String foodName)</span> &#123;</span><br><span class="line">        System.out.println(num + <span class="string">&quot;份&quot;</span> + foodName);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Waitor</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> ArrayList&lt;Command&gt; commands;<span class="comment">//可以持有很多的命令对象</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Waitor</span><span class="params">()</span> &#123;</span><br><span class="line">        commands = <span class="keyword">new</span> <span class="title class_">ArrayList</span>();</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setCommand</span><span class="params">(Command cmd)</span>&#123;</span><br><span class="line">        commands.add(cmd);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 发出命令 喊 订单来了，厨师开始执行</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">orderUp</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;美女服务员：叮咚，大厨，新订单来了.......&quot;</span>);</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; commands.size(); i++) &#123;</span><br><span class="line">            <span class="type">Command</span> <span class="variable">cmd</span> <span class="operator">=</span> commands.get(i);</span><br><span class="line">            <span class="keyword">if</span> (cmd != <span class="literal">null</span>) &#123;</span><br><span class="line">                cmd.execute();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Client</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="comment">//创建2个order</span></span><br><span class="line">        <span class="type">Order</span> <span class="variable">order1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Order</span>();</span><br><span class="line">        order1.setDiningTable(<span class="number">1</span>);</span><br><span class="line">        order1.getFoodDic().put(<span class="string">&quot;西红柿鸡蛋面&quot;</span>,<span class="number">1</span>);</span><br><span class="line">        order1.getFoodDic().put(<span class="string">&quot;小杯可乐&quot;</span>,<span class="number">2</span>);</span><br><span class="line"></span><br><span class="line">        <span class="type">Order</span> <span class="variable">order2</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Order</span>();</span><br><span class="line">        order2.setDiningTable(<span class="number">3</span>);</span><br><span class="line">        order2.getFoodDic().put(<span class="string">&quot;尖椒肉丝盖饭&quot;</span>,<span class="number">1</span>);</span><br><span class="line">        order2.getFoodDic().put(<span class="string">&quot;小杯雪碧&quot;</span>,<span class="number">1</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建接收者</span></span><br><span class="line">        SeniorChef receiver=<span class="keyword">new</span> <span class="title class_">SeniorChef</span>();</span><br><span class="line">        <span class="comment">//将订单和接收者封装成命令对象</span></span><br><span class="line">        <span class="type">OrderCommand</span> <span class="variable">cmd1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">OrderCommand</span>(receiver, order1);</span><br><span class="line">        <span class="type">OrderCommand</span> <span class="variable">cmd2</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">OrderCommand</span>(receiver, order2);</span><br><span class="line">        <span class="comment">//创建调用者 waitor</span></span><br><span class="line">        <span class="type">Waitor</span> <span class="variable">invoker</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Waitor</span>();</span><br><span class="line">        invoker.setCommand(cmd1);</span><br><span class="line">        invoker.setCommand(cmd2);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//将订单带到柜台 并向厨师喊 订单来了</span></span><br><span class="line">        invoker.orderUp();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<h3 id="634-优缺点"><a class="markdownIt-Anchor" href="#634-优缺点">#</a> 6.3.4 优缺点</h3>
<p><strong>1，优点：</strong></p>
<ul>
<li>降低系统的耦合度。命令模式能将调用操作的对象与实现该操作的对象解耦。</li>
<li>增加或删除命令非常方便。采用命令模式增加与删除命令不会影响其他类，它满足 “开闭原则”，对扩展比较灵活。</li>
<li>可以实现宏命令。命令模式可以与组合模式结合，将多个命令装配成一个组合命令，即宏命令。</li>
<li>方便实现 Undo 和 Redo 操作。命令模式可以与后面介绍的备忘录模式结合，实现命令的撤销与恢复。</li>
</ul>
<p><strong>2，缺点：</strong></p>
<ul>
<li>使用命令模式可能会导致某些系统有过多的具体命令类。</li>
<li>系统结构更加复杂。</li>
</ul>
<h3 id="635-使用场景"><a class="markdownIt-Anchor" href="#635-使用场景">#</a> 6.3.5 使用场景</h3>
<ul>
<li>系统需要将请求调用者和请求接收者解耦，使得调用者和接收者不直接交互。</li>
<li>系统需要在不同的时间指定请求、将请求排队和执行请求。</li>
<li>系统需要支持命令的撤销 (Undo) 操作和恢复 (Redo) 操作。</li>
</ul>
<h3 id="636-jdk源码解析"><a class="markdownIt-Anchor" href="#636-jdk源码解析">#</a> 6.3.6 JDK 源码解析</h3>
<p>Runable 是一个典型命令模式，Runnable 担当命令的角色，Thread 充当的是调用者，start 方法就是其执行方法</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//命令接口(抽象命令角色)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">Runnable</span> &#123;</span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//调用者</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Thread</span> <span class="keyword">implements</span> <span class="title class_">Runnable</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> Runnable target;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title function_">start</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (threadStatus != <span class="number">0</span>)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">IllegalThreadStateException</span>();</span><br><span class="line"></span><br><span class="line">        group.add(<span class="built_in">this</span>);</span><br><span class="line"></span><br><span class="line">        <span class="type">boolean</span> <span class="variable">started</span> <span class="operator">=</span> <span class="literal">false</span>;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            start0();</span><br><span class="line">            started = <span class="literal">true</span>;</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="keyword">if</span> (!started) &#123;</span><br><span class="line">                    group.threadStartFailed(<span class="built_in">this</span>);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">catch</span> (Throwable ignore) &#123;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">native</span> <span class="keyword">void</span> <span class="title function_">start0</span><span class="params">()</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>会调用一个 native 方法 start0 (), 调用系统方法，开启一个线程。而接收者是对程序员开放的，可以自己定义接收者。</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * jdk Runnable 命令模式</span></span><br><span class="line"><span class="comment"> *		TurnOffThread ： 属于具体</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TurnOffThread</span> <span class="keyword">implements</span> <span class="title class_">Runnable</span>&#123;</span><br><span class="line">     <span class="keyword">private</span> Receiver receiver;</span><br><span class="line">    </span><br><span class="line">     <span class="keyword">public</span> <span class="title function_">TurnOffThread</span><span class="params">(Receiver receiver)</span> &#123;</span><br><span class="line">     	<span class="built_in">this</span>.receiver = receiver;</span><br><span class="line">     &#125;</span><br><span class="line">     <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">     	receiver.turnOFF();</span><br><span class="line">     &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 测试类</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Demo</span> &#123;</span><br><span class="line">     <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">         <span class="type">Receiver</span> <span class="variable">receiver</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Receiver</span>();</span><br><span class="line">         <span class="type">TurnOffThread</span> <span class="variable">turnOffThread</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">TurnOffThread</span>(receiver);</span><br><span class="line">         <span class="type">Thread</span> <span class="variable">thread</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Thread</span>(turnOffThread);</span><br><span class="line">         thread.start();</span><br><span class="line">     &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<h2 id="64-责任链模式"><a class="markdownIt-Anchor" href="#64-责任链模式">#</a> 6.4 责任链模式</h2>
<h3 id="641-概述"><a class="markdownIt-Anchor" href="#641-概述">#</a> 6.4.1 概述</h3>
<p>在现实生活中，常常会出现这样的事例：一个请求有多个对象可以处理，但每个对象的处理条件或权限不同。例如，公司员工请假，可批假的领导有部门负责人、副总经理、总经理等，但每个领导能批准的天数不同，员工必须根据自己要请假的天数去找不同的领导签名，也就是说员工必须记住每个领导的姓名、电话和地址等信息，这增加了难度。这样的例子还有很多，如找领导出差报销、生活中的 “击鼓传花” 游戏等。</p>
<p><strong>定义：</strong></p>
<p>又名职责链模式，为了避免请求发送者与多个请求处理者耦合在一起，将所有请求的处理者通过前一对象记住其下一个对象的引用而连成一条链；当有请求发生时，可将请求沿着这条链传递，直到有对象处理它为止。</p>
<h3 id="642-结构"><a class="markdownIt-Anchor" href="#642-结构">#</a> 6.4.2 结构</h3>
<p>职责链模式主要包含以下角色:</p>
<ul>
<li>抽象处理者（Handler）角色：定义一个处理请求的接口，包含抽象处理方法和一个后继连接。</li>
<li>具体处理者（Concrete Handler）角色：实现抽象处理者的处理方法，判断能否处理本次请求，如果可以处理请求则处理，否则将该请求转给它的后继者。</li>
<li>客户类（Client）角色：创建处理链，并向链头的具体处理者对象提交请求，它不关心处理细节和请求的传递过程。</li>
</ul>
<h3 id="643-案例实现"><a class="markdownIt-Anchor" href="#643-案例实现">#</a> 6.4.3 案例实现</h3>
<p>现需要开发一个请假流程控制系统。请假一天以下的假只需要小组长同意即可；请假 1 天到 3 天的假还需要部门经理同意；请求 3 天到 7 天还需要总经理同意才行。</p>
<p>类图如下：<br>
<img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420232023190.png"
                      alt="在这里插入图片描述"
                ></p>
<p>代码如下：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//请假条</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">LeaveRequest</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> String name;<span class="comment">//姓名</span></span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> num;<span class="comment">//请假天数</span></span><br><span class="line">    <span class="keyword">private</span> String content;<span class="comment">//请假内容</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">LeaveRequest</span><span class="params">(String name, <span class="type">int</span> num, String content)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.name = name;</span><br><span class="line">        <span class="built_in">this</span>.num = num;</span><br><span class="line">        <span class="built_in">this</span>.content = content;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getName</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">getNum</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> num;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getContent</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> content;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//处理者抽象类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title class_">Handler</span> &#123;</span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">final</span> <span class="keyword">static</span> <span class="type">int</span> <span class="variable">NUM_ONE</span> <span class="operator">=</span> <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">final</span> <span class="keyword">static</span> <span class="type">int</span> <span class="variable">NUM_THREE</span> <span class="operator">=</span> <span class="number">3</span>;</span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">final</span> <span class="keyword">static</span> <span class="type">int</span> <span class="variable">NUM_SEVEN</span> <span class="operator">=</span> <span class="number">7</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//该领导处理的请假天数区间</span></span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> numStart;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> numEnd;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//领导上面还有领导</span></span><br><span class="line">    <span class="keyword">private</span> Handler nextHandler;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//设置请假天数范围 上不封顶</span></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Handler</span><span class="params">(<span class="type">int</span> numStart)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.numStart = numStart;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//设置请假天数范围</span></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Handler</span><span class="params">(<span class="type">int</span> numStart, <span class="type">int</span> numEnd)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.numStart = numStart;</span><br><span class="line">        <span class="built_in">this</span>.numEnd = numEnd;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//设置上级领导</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setNextHandler</span><span class="params">(Handler nextHandler)</span>&#123;</span><br><span class="line">        <span class="built_in">this</span>.nextHandler = nextHandler;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//提交请假条</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title function_">submit</span><span class="params">(LeaveRequest leave)</span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(<span class="number">0</span> == <span class="built_in">this</span>.numStart)&#123;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//如果请假天数达到该领导者的处理要求</span></span><br><span class="line">        <span class="keyword">if</span>(leave.getNum() &gt;= <span class="built_in">this</span>.numStart)&#123;</span><br><span class="line">            <span class="built_in">this</span>.handleLeave(leave);</span><br><span class="line"></span><br><span class="line">            <span class="comment">//如果还有上级 并且请假天数超过了当前领导的处理范围</span></span><br><span class="line">            <span class="keyword">if</span>(<span class="literal">null</span> != <span class="built_in">this</span>.nextHandler &amp;&amp; leave.getNum() &gt; numEnd)&#123;</span><br><span class="line">                <span class="built_in">this</span>.nextHandler.submit(leave);<span class="comment">//继续提交</span></span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;流程结束&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//各级领导处理请假条方法</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title function_">handleLeave</span><span class="params">(LeaveRequest leave)</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//小组长</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">GroupLeader</span> <span class="keyword">extends</span> <span class="title class_">Handler</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">GroupLeader</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="comment">//小组长处理1-3天的请假</span></span><br><span class="line">        <span class="built_in">super</span>(Handler.NUM_ONE, Handler.NUM_THREE);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">handleLeave</span><span class="params">(LeaveRequest leave)</span> &#123;</span><br><span class="line">        System.out.println(leave.getName() + <span class="string">&quot;请假&quot;</span> + leave.getNum() + <span class="string">&quot;天,&quot;</span> + leave.getContent() + <span class="string">&quot;。&quot;</span>);</span><br><span class="line">        System.out.println(<span class="string">&quot;小组长审批：同意。&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//部门经理</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Manager</span> <span class="keyword">extends</span> <span class="title class_">Handler</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Manager</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="comment">//部门经理处理3-7天的请假</span></span><br><span class="line">        <span class="built_in">super</span>(Handler.NUM_THREE, Handler.NUM_SEVEN);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">handleLeave</span><span class="params">(LeaveRequest leave)</span> &#123;</span><br><span class="line">        System.out.println(leave.getName() + <span class="string">&quot;请假&quot;</span> + leave.getNum() + <span class="string">&quot;天,&quot;</span> + leave.getContent() + <span class="string">&quot;。&quot;</span>);</span><br><span class="line">        System.out.println(<span class="string">&quot;部门经理审批：同意。&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//总经理</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">GeneralManager</span> <span class="keyword">extends</span> <span class="title class_">Handler</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">GeneralManager</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="comment">//部门经理处理7天以上的请假</span></span><br><span class="line">        <span class="built_in">super</span>(Handler.NUM_SEVEN);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">handleLeave</span><span class="params">(LeaveRequest leave)</span> &#123;</span><br><span class="line">        System.out.println(leave.getName() + <span class="string">&quot;请假&quot;</span> + leave.getNum() + <span class="string">&quot;天,&quot;</span> + leave.getContent() + <span class="string">&quot;。&quot;</span>);</span><br><span class="line">        System.out.println(<span class="string">&quot;总经理审批：同意。&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//测试类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Client</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="comment">//请假条来一张</span></span><br><span class="line">        <span class="type">LeaveRequest</span> <span class="variable">leave</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">LeaveRequest</span>(<span class="string">&quot;小花&quot;</span>,<span class="number">5</span>,<span class="string">&quot;身体不适&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//各位领导</span></span><br><span class="line">        <span class="type">GroupLeader</span> <span class="variable">groupLeader</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">GroupLeader</span>();</span><br><span class="line">        <span class="type">Manager</span> <span class="variable">manager</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Manager</span>();</span><br><span class="line">        <span class="type">GeneralManager</span> <span class="variable">generalManager</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">GeneralManager</span>();</span><br><span class="line"></span><br><span class="line">        groupLeader.setNextHandler(manager);<span class="comment">//小组长的领导是部门经理</span></span><br><span class="line">        manager.setNextHandler(generalManager);<span class="comment">//部门经理的领导是总经理</span></span><br><span class="line">        <span class="comment">//之所以在这里设置上级领导，是因为可以根据实际需求来更改设置，如果实战中上级领导人都是固定的，则可以移到领导实现类中。</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//提交申请</span></span><br><span class="line">        groupLeader.submit(leave);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<h3 id="644-优缺点"><a class="markdownIt-Anchor" href="#644-优缺点">#</a> 6.4.4 优缺点</h3>
<p><strong>1，优点：</strong></p>
<ul>
<li>
<p>降低了对象之间的耦合度</p>
<p>该模式降低了请求发送者和接收者的耦合度。</p>
</li>
<li>
<p>增强了系统的可扩展性</p>
<p>可以根据需要增加新的请求处理类，满足开闭原则。</p>
</li>
<li>
<p>增强了给对象指派职责的灵活性</p>
<p>当工作流程发生变化，可以动态地改变链内的成员或者修改它们的次序，也可动态地新增或者删除责任。</p>
</li>
<li>
<p>责任链简化了对象之间的连接</p>
<p>一个对象只需保持一个指向其后继者的引用，不需保持其他所有处理者的引用，这避免了使用众多的 if 或者 if・・・else 语句。</p>
</li>
<li>
<p>责任分担</p>
<p>每个类只需要处理自己该处理的工作，不能处理的传递给下一个对象完成，明确各类的责任范围，符合类的单一职责原则。</p>
</li>
</ul>
<p><strong>2，缺点：</strong></p>
<ul>
<li>不能保证每个请求一定被处理。由于一个请求没有明确的接收者，所以不能保证它一定会被处理，该请求可能一直传到链的末端都得不到处理。</li>
<li>对比较长的职责链，请求的处理可能涉及多个处理对象，系统性能将受到一定影响。</li>
<li>职责链建立的合理性要靠客户端来保证，增加了客户端的复杂性，可能会由于职责链的错误设置而导致系统出错，如可能会造成循环调用。</li>
</ul>
<h3 id="645-源码解析"><a class="markdownIt-Anchor" href="#645-源码解析">#</a> 6.4.5 源码解析</h3>
<p>在 javaWeb 应用开发中，FilterChain 是职责链（过滤器）模式的典型应用，以下是 Filter 的模拟实现分析:</p>
<ul>
<li>
<p>模拟 web 请求 Request 以及 web 响应 Response</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">Request</span>&#123;</span><br><span class="line"> </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">Response</span>&#123;</span><br><span class="line"> </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
</li>
<li>
<p>模拟 web 过滤器 Filter</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">Filter</span> &#123;</span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">doFilter</span><span class="params">(Request req,Response res,FilterChain c)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
</li>
<li>
<p>模拟实现具体过滤器</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">FirstFilter</span> <span class="keyword">implements</span> <span class="title class_">Filter</span> &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">doFilter</span><span class="params">(Request request, Response response, FilterChain chain)</span> &#123;</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;过滤器1 前置处理&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 先执行所有request再倒序执行所有response</span></span><br><span class="line">        chain.doFilter(request, response);</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;过滤器1 后置处理&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">SecondFilter</span>  <span class="keyword">implements</span> <span class="title class_">Filter</span> &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">doFilter</span><span class="params">(Request request, Response response, FilterChain chain)</span> &#123;</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;过滤器2 前置处理&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 先执行所有request再倒序执行所有response</span></span><br><span class="line">        chain.doFilter(request, response);</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;过滤器2 后置处理&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
</li>
<li>
<p>模拟实现过滤器链 FilterChain</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">FilterChain</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> List&lt;Filter&gt; filters = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;Filter&gt;();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> <span class="variable">index</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 链式调用</span></span><br><span class="line">    <span class="keyword">public</span> FilterChain <span class="title function_">addFilter</span><span class="params">(Filter filter)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.filters.add(filter);</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">doFilter</span><span class="params">(Request request, Response response)</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (index == filters.size()) &#123;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="type">Filter</span> <span class="variable">filter</span> <span class="operator">=</span> filters.get(index);</span><br><span class="line">        index++;</span><br><span class="line">        filter.doFilter(request, response, <span class="built_in">this</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
</li>
<li>
<p>测试类</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Client</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">Request</span>  <span class="variable">req</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">        <span class="type">Response</span> <span class="variable">res</span> <span class="operator">=</span> <span class="literal">null</span> ;</span><br><span class="line"></span><br><span class="line">        <span class="type">FilterChain</span> <span class="variable">filterChain</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">FilterChain</span>();</span><br><span class="line">        filterChain.addFilter(<span class="keyword">new</span> <span class="title class_">FirstFilter</span>()).addFilter(<span class="keyword">new</span> <span class="title class_">SecondFilter</span>());</span><br><span class="line">        filterChain.doFilter(req,res);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
</li>
</ul>
<h2 id="65-状态模式"><a class="markdownIt-Anchor" href="#65-状态模式">#</a> 6.5 状态模式</h2>
<h3 id="651-概述"><a class="markdownIt-Anchor" href="#651-概述">#</a> 6.5.1 概述</h3>
<p>【例】通过按钮来控制一个电梯的状态，一个电梯有开门状态，关门状态，停止状态，运行状态。每一种状态改变，都有可能要根据其他状态来更新处理。例如，如果电梯门现在处于运行时状态，就不能进行开门操作，而如果电梯门是停止状态，就可以执行开门操作。</p>
<p>类图如下：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420232039369.png"
                      alt="在这里插入图片描述"
                ></p>
<p>代码如下：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">ILift</span> &#123;</span><br><span class="line">    <span class="comment">//电梯的4个状态</span></span><br><span class="line">    <span class="comment">//开门状态</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">static</span> <span class="type">int</span> <span class="variable">OPENING_STATE</span> <span class="operator">=</span> <span class="number">1</span>;</span><br><span class="line">    <span class="comment">//关门状态</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">static</span> <span class="type">int</span> <span class="variable">CLOSING_STATE</span> <span class="operator">=</span> <span class="number">2</span>;</span><br><span class="line">    <span class="comment">//运行状态</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">static</span> <span class="type">int</span> <span class="variable">RUNNING_STATE</span> <span class="operator">=</span> <span class="number">3</span>;</span><br><span class="line">    <span class="comment">//停止状态</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">static</span> <span class="type">int</span> <span class="variable">STOPPING_STATE</span> <span class="operator">=</span> <span class="number">4</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//设置电梯的状态</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setState</span><span class="params">(<span class="type">int</span> state)</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//电梯的动作</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">open</span><span class="params">()</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">close</span><span class="params">()</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">stop</span><span class="params">()</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Lift</span> <span class="keyword">implements</span> <span class="title class_">ILift</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> state;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setState</span><span class="params">(<span class="type">int</span> state)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.state = state;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//执行关门动作</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">close</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">switch</span> (<span class="built_in">this</span>.state) &#123;</span><br><span class="line">            <span class="keyword">case</span> OPENING_STATE:</span><br><span class="line">                System.out.println(<span class="string">&quot;电梯关门了。。。&quot;</span>);<span class="comment">//只有开门状态可以关闭电梯门，可以对应电梯状态表来看</span></span><br><span class="line">                <span class="built_in">this</span>.setState(CLOSING_STATE);<span class="comment">//关门之后电梯就是关闭状态了</span></span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> CLOSING_STATE:</span><br><span class="line">                <span class="comment">//do nothing //已经是关门状态，不能关门</span></span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> RUNNING_STATE:</span><br><span class="line">                <span class="comment">//do nothing //运行时电梯门是关着的，不能关门</span></span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> STOPPING_STATE:</span><br><span class="line">                <span class="comment">//do nothing //停止时电梯也是关着的，不能关门</span></span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//执行开门动作</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">open</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">switch</span> (<span class="built_in">this</span>.state) &#123;</span><br><span class="line">            <span class="keyword">case</span> OPENING_STATE:<span class="comment">//门已经开了，不能再开门了</span></span><br><span class="line">                <span class="comment">//do nothing</span></span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> CLOSING_STATE:<span class="comment">//关门状态，门打开:</span></span><br><span class="line">                System.out.println(<span class="string">&quot;电梯门打开了。。。&quot;</span>);</span><br><span class="line">                <span class="built_in">this</span>.setState(OPENING_STATE);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> RUNNING_STATE:</span><br><span class="line">                <span class="comment">//do nothing 运行时电梯不能开门</span></span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> STOPPING_STATE:</span><br><span class="line">                System.out.println(<span class="string">&quot;电梯门开了。。。&quot;</span>);<span class="comment">//电梯停了，可以开门了</span></span><br><span class="line">                <span class="built_in">this</span>.setState(OPENING_STATE);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//执行运行动作</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">switch</span> (<span class="built_in">this</span>.state) &#123;</span><br><span class="line">            <span class="keyword">case</span> OPENING_STATE:<span class="comment">//电梯不能开着门就走</span></span><br><span class="line">                <span class="comment">//do nothing</span></span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> CLOSING_STATE:<span class="comment">//门关了，可以运行了</span></span><br><span class="line">                System.out.println(<span class="string">&quot;电梯开始运行了。。。&quot;</span>);</span><br><span class="line">                <span class="built_in">this</span>.setState(RUNNING_STATE);<span class="comment">//现在是运行状态</span></span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> RUNNING_STATE:</span><br><span class="line">                <span class="comment">//do nothing 已经是运行状态了</span></span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> STOPPING_STATE:</span><br><span class="line">                System.out.println(<span class="string">&quot;电梯开始运行了。。。&quot;</span>);</span><br><span class="line">                <span class="built_in">this</span>.setState(RUNNING_STATE);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//执行停止动作</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">stop</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">switch</span> (<span class="built_in">this</span>.state) &#123;</span><br><span class="line">            <span class="keyword">case</span> OPENING_STATE: <span class="comment">//开门的电梯已经是是停止的了(正常情况下)</span></span><br><span class="line">                <span class="comment">//do nothing</span></span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> CLOSING_STATE:<span class="comment">//关门时才可以停止</span></span><br><span class="line">                System.out.println(<span class="string">&quot;电梯停止了。。。&quot;</span>);</span><br><span class="line">                <span class="built_in">this</span>.setState(STOPPING_STATE);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> RUNNING_STATE:<span class="comment">//运行时当然可以停止了</span></span><br><span class="line">                System.out.println(<span class="string">&quot;电梯停止了。。。&quot;</span>);</span><br><span class="line">                <span class="built_in">this</span>.setState(STOPPING_STATE);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> STOPPING_STATE:</span><br><span class="line">                <span class="comment">//do nothing</span></span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Client</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">Lift</span> <span class="variable">lift</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Lift</span>();</span><br><span class="line">        lift.setState(ILift.STOPPING_STATE);<span class="comment">//电梯是停止的</span></span><br><span class="line">        lift.open();<span class="comment">//开门</span></span><br><span class="line">        lift.close();<span class="comment">//关门</span></span><br><span class="line">        lift.run();<span class="comment">//运行</span></span><br><span class="line">        lift.stop();<span class="comment">//停止</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>问题分析：</p>
<ul>
<li>使用了大量的 switch…case 这样的判断（if…else 也是一样)，使程序的可阅读性变差。</li>
<li>扩展性很差。如果新加了断电的状态，我们需要修改上面判断逻辑</li>
</ul>
<p><strong>定义：</strong></p>
<p>对有状态的对象，把复杂的 “判断逻辑” 提取到不同的状态对象中，允许状态对象在其内部状态发生改变时改变其行为。</p>
<h3 id="652-结构"><a class="markdownIt-Anchor" href="#652-结构">#</a> 6.5.2 结构</h3>
<p>状态模式包含以下主要角色。</p>
<ul>
<li>环境（Context）角色：也称为上下文，它定义了客户程序需要的接口，维护一个当前状态，并将与状态相关的操作委托给当前状态对象来处理。</li>
<li>抽象状态（State）角色：定义一个接口，用以封装环境对象中的特定状态所对应的行为。</li>
<li>具体状态（Concrete  State）角色：实现抽象状态所对应的行为。</li>
</ul>
<h3 id="653-案例实现"><a class="markdownIt-Anchor" href="#653-案例实现">#</a> 6.5.3 案例实现</h3>
<p>对上述电梯的案例使用状态模式进行改进。类图如下：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420232053415.png"
                      alt="在这里插入图片描述"
                ></p>
<p>代码如下：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//抽象状态类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title class_">LiftState</span> &#123;</span><br><span class="line">    <span class="comment">//定义一个环境角色，也就是封装状态的变化引起的功能变化</span></span><br><span class="line">    <span class="keyword">protected</span> Context context;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setContext</span><span class="params">(Context context)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.context = context;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//电梯开门动作</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title function_">open</span><span class="params">()</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//电梯关门动作</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title function_">close</span><span class="params">()</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//电梯运行动作</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//电梯停止动作</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title function_">stop</span><span class="params">()</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//开启状态</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">OpenningState</span> <span class="keyword">extends</span> <span class="title class_">LiftState</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//开启当然可以关闭了，我就想测试一下电梯门开关功能</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">open</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;电梯门开启...&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">close</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="comment">//状态修改</span></span><br><span class="line">        <span class="built_in">super</span>.context.setLiftState(Context.closeingState);</span><br><span class="line">        <span class="comment">//动作委托为CloseState来执行，也就是委托给了ClosingState子类执行这个动作</span></span><br><span class="line">        <span class="built_in">super</span>.context.getLiftState().close();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//电梯门不能开着就跑，这里什么也不做</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="comment">//do nothing</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//开门状态已经是停止的了</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">stop</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="comment">//do nothing</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//运行状态</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">RunningState</span> <span class="keyword">extends</span> <span class="title class_">LiftState</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//运行的时候开电梯门？你疯了！电梯不会给你开的</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">open</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="comment">//do nothing</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//电梯门关闭？这是肯定了</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">close</span><span class="params">()</span> &#123;<span class="comment">//虽然可以关门，但这个动作不归我执行</span></span><br><span class="line">        <span class="comment">//do nothing</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//这是在运行状态下要实现的方法</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;电梯正在运行...&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//这个事绝对是合理的，光运行不停止还有谁敢做这个电梯？！估计只有上帝了</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">stop</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="built_in">super</span>.context.setLiftState(Context.stoppingState);</span><br><span class="line">        <span class="built_in">super</span>.context.stop();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//停止状态</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">StoppingState</span> <span class="keyword">extends</span> <span class="title class_">LiftState</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//停止状态，开门，那是要的！</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">open</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="comment">//状态修改</span></span><br><span class="line">        <span class="built_in">super</span>.context.setLiftState(Context.openningState);</span><br><span class="line">        <span class="comment">//动作委托为CloseState来执行，也就是委托给了ClosingState子类执行这个动作</span></span><br><span class="line">        <span class="built_in">super</span>.context.getLiftState().open();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">close</span><span class="params">()</span> &#123;<span class="comment">//虽然可以关门，但这个动作不归我执行</span></span><br><span class="line">        <span class="comment">//状态修改</span></span><br><span class="line">        <span class="built_in">super</span>.context.setLiftState(Context.closeingState);</span><br><span class="line">        <span class="comment">//动作委托为CloseState来执行，也就是委托给了ClosingState子类执行这个动作</span></span><br><span class="line">        <span class="built_in">super</span>.context.getLiftState().close();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//停止状态再跑起来，正常的很</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="comment">//状态修改</span></span><br><span class="line">        <span class="built_in">super</span>.context.setLiftState(Context.runningState);</span><br><span class="line">        <span class="comment">//动作委托为CloseState来执行，也就是委托给了ClosingState子类执行这个动作</span></span><br><span class="line">        <span class="built_in">super</span>.context.getLiftState().run();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//停止状态是怎么发生的呢？当然是停止方法执行了</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">stop</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;电梯停止了...&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//关闭状态</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ClosingState</span> <span class="keyword">extends</span> <span class="title class_">LiftState</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="comment">//电梯门关闭，这是关闭状态要实现的动作</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">close</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;电梯门关闭...&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//电梯门关了再打开，逗你玩呢，那这个允许呀</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">open</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="built_in">super</span>.context.setLiftState(Context.openningState);</span><br><span class="line">        <span class="built_in">super</span>.context.open();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">//电梯门关了就跑，这是再正常不过了</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="built_in">super</span>.context.setLiftState(Context.runningState);</span><br><span class="line">        <span class="built_in">super</span>.context.run();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//电梯门关着，我就不按楼层</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">stop</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="built_in">super</span>.context.setLiftState(Context.stoppingState);</span><br><span class="line">        <span class="built_in">super</span>.context.stop();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//环境角色</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Context</span> &#123;</span><br><span class="line">    <span class="comment">//定义出所有的电梯状态</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">static</span> <span class="type">OpenningState</span> <span class="variable">openningState</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">OpenningState</span>();<span class="comment">//开门状态，这时候电梯只能关闭</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">static</span> <span class="type">ClosingState</span> <span class="variable">closeingState</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ClosingState</span>();<span class="comment">//关闭状态，这时候电梯可以运行、停止和开门</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">static</span> <span class="type">RunningState</span> <span class="variable">runningState</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">RunningState</span>();<span class="comment">//运行状态，这时候电梯只能停止</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">static</span> <span class="type">StoppingState</span> <span class="variable">stoppingState</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">StoppingState</span>();<span class="comment">//停止状态，这时候电梯可以开门、运行</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">//定义一个当前电梯状态</span></span><br><span class="line">    <span class="keyword">private</span> LiftState liftState;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> LiftState <span class="title function_">getLiftState</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span>.liftState;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setLiftState</span><span class="params">(LiftState liftState)</span> &#123;</span><br><span class="line">        <span class="comment">//当前环境改变</span></span><br><span class="line">        <span class="built_in">this</span>.liftState = liftState;</span><br><span class="line">        <span class="comment">//把当前的环境通知到各个实现类中</span></span><br><span class="line">        <span class="built_in">this</span>.liftState.setContext(<span class="built_in">this</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">open</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.liftState.open();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">close</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.liftState.close();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.liftState.run();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">stop</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.liftState.stop();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//测试类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Client</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">Context</span> <span class="variable">context</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Context</span>();</span><br><span class="line">        context.setLiftState(<span class="keyword">new</span> <span class="title class_">ClosingState</span>());</span><br><span class="line"></span><br><span class="line">        context.open();</span><br><span class="line">        context.close();</span><br><span class="line">        context.run();</span><br><span class="line">        context.stop();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<h3 id="654-优缺点"><a class="markdownIt-Anchor" href="#654-优缺点">#</a> 6.5.4 优缺点</h3>
<p><strong>1，优点：</strong></p>
<ul>
<li>将所有与某个状态有关的行为放到一个类中，并且可以方便地增加新的状态，只需要改变对象状态即可改变对象的行为。</li>
<li>允许状态转换逻辑与状态对象合成一体，而不是某一个巨大的条件语句块。</li>
</ul>
<p><strong>2，缺点：</strong></p>
<ul>
<li>状态模式的使用必然会增加系统类和对象的个数。</li>
<li>状态模式的结构与实现都较为复杂，如果使用不当将导致程序结构和代码的混乱。</li>
<li>状态模式对 &quot;开闭原则&quot; 的支持并不太好。</li>
</ul>
<h3 id="655-使用场景"><a class="markdownIt-Anchor" href="#655-使用场景">#</a> 6.5.5 使用场景</h3>
<ul>
<li>当一个对象的行为取决于它的状态，并且它必须在运行时根据状态改变它的行为时，就可以考虑使用状态模式。</li>
<li>一个操作中含有庞大的分支结构，并且这些分支决定于对象的状态时。</li>
</ul>
<h2 id="66-观察者模式"><a class="markdownIt-Anchor" href="#66-观察者模式">#</a> 6.6 观察者模式</h2>
<h3 id="661-概述"><a class="markdownIt-Anchor" href="#661-概述">#</a> 6.6.1 概述</h3>
<p><strong>定义：</strong></p>
<p>又被称为发布 - 订阅（Publish/Subscribe）模式，它定义了一种一对多的依赖关系，让多个观察者对象同时监听某一个主题对象。这个主题对象在状态变化时，会通知所有的观察者对象，使他们能够自动更新自己。</p>
<h3 id="662-结构"><a class="markdownIt-Anchor" href="#662-结构">#</a> 6.6.2 结构</h3>
<p>在观察者模式中有如下角色：</p>
<ul>
<li>Subject：抽象主题（抽象被观察者），抽象主题角色把所有观察者对象保存在一个集合里，每个主题都可以有任意数量的观察者，抽象主题提供一个接口，可以增加和删除观察者对象。</li>
<li>ConcreteSubject：具体主题（具体被观察者），该角色将有关状态存入具体观察者对象，在具体主题的内部状态发生改变时，给所有注册过的观察者发送通知。</li>
<li>Observer：抽象观察者，是观察者的抽象类，它定义了一个更新接口，使得在得到主题更改通知时更新自己。</li>
<li>ConcrereObserver：具体观察者，实现抽象观察者定义的更新接口，以便在得到主题更改通知时更新自身的状态。</li>
</ul>
<h3 id="663-案例实现"><a class="markdownIt-Anchor" href="#663-案例实现">#</a> 6.6.3 案例实现</h3>
<p>【例】微信公众号</p>
<p>在使用微信公众号时，大家都会有这样的体验，当你关注的公众号中有新内容更新的话，它就会推送给关注公众号的微信用户端。我们使用观察者模式来模拟这样的场景，微信用户就是观察者，微信公众号是被观察者，有多个的微信用户关注了程序猿这个公众号。</p>
<p>类图如下：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420232124135.png"
                      alt="在这里插入图片描述"
                ></p>
<p>代码如下：</p>
<p>定义抽象观察者类，里面定义一个更新的方法</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">Observer</span> &#123;</span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">update</span><span class="params">(String message)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>定义具体观察者类，微信用户是观察者，里面实现了更新的方法</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">WeixinUser</span> <span class="keyword">implements</span> <span class="title class_">Observer</span> &#123;</span><br><span class="line">    <span class="comment">// 微信用户名</span></span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">WeixinUser</span><span class="params">(String name)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">update</span><span class="params">(String message)</span> &#123;</span><br><span class="line">        System.out.println(name + <span class="string">&quot;-&quot;</span> + message);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>定义抽象主题类，提供了 attach、detach、notify 三个方法</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">Subject</span> &#123;</span><br><span class="line">    <span class="comment">//增加订阅者</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">attach</span><span class="params">(Observer observer)</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//删除订阅者</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">detach</span><span class="params">(Observer observer)</span>;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//通知订阅者更新消息</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">notify</span><span class="params">(String message)</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure></div>
<p>微信公众号是具体主题（具体被观察者），里面存储了订阅该公众号的微信用户，并实现了抽象主题中的方法</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">SubscriptionSubject</span> <span class="keyword">implements</span> <span class="title class_">Subject</span> &#123;</span><br><span class="line">    <span class="comment">//储存订阅公众号的微信用户</span></span><br><span class="line">    <span class="keyword">private</span> List&lt;Observer&gt; weixinUserlist = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;Observer&gt;();</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">attach</span><span class="params">(Observer observer)</span> &#123;</span><br><span class="line">        weixinUserlist.add(observer);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">detach</span><span class="params">(Observer observer)</span> &#123;</span><br><span class="line">        weixinUserlist.remove(observer);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">notify</span><span class="params">(String message)</span> &#123;</span><br><span class="line">        <span class="keyword">for</span> (Observer observer : weixinUserlist) &#123;</span><br><span class="line">            observer.update(message);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>客户端程序</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Client</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        SubscriptionSubject mSubscriptionSubject=<span class="keyword">new</span> <span class="title class_">SubscriptionSubject</span>();</span><br><span class="line">        <span class="comment">//创建微信用户</span></span><br><span class="line">        WeixinUser user1=<span class="keyword">new</span> <span class="title class_">WeixinUser</span>(<span class="string">&quot;孙悟空&quot;</span>);</span><br><span class="line">        WeixinUser user2=<span class="keyword">new</span> <span class="title class_">WeixinUser</span>(<span class="string">&quot;猪悟能&quot;</span>);</span><br><span class="line">        WeixinUser user3=<span class="keyword">new</span> <span class="title class_">WeixinUser</span>(<span class="string">&quot;沙悟净&quot;</span>);</span><br><span class="line">        <span class="comment">//订阅公众号</span></span><br><span class="line">        mSubscriptionSubject.attach(user1);</span><br><span class="line">        mSubscriptionSubject.attach(user2);</span><br><span class="line">        mSubscriptionSubject.attach(user3);</span><br><span class="line">        <span class="comment">//公众号更新发出消息给订阅的微信用户</span></span><br><span class="line">        mSubscriptionSubject.notify(<span class="string">&quot;传智黑马的专栏更新了&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure></div>
<h3 id="664-优缺点"><a class="markdownIt-Anchor" href="#664-优缺点">#</a> 6.6.4 优缺点</h3>
<p><strong>1，优点：</strong></p>
<ul>
<li>降低了目标与观察者之间的耦合关系，两者之间是抽象耦合关系。</li>
<li>被观察者发送通知，所有注册的观察者都会收到信息【可以实现广播机制】</li>
</ul>
<p><strong>2，缺点：</strong></p>
<ul>
<li>如果观察者非常多的话，那么所有的观察者收到被观察者发送的通知会耗时</li>
<li>如果被观察者有循环依赖的话，那么被观察者发送通知会使观察者循环调用，会导致系统崩溃</li>
</ul>
<h3 id="665-使用场景"><a class="markdownIt-Anchor" href="#665-使用场景">#</a> 6.6.5 使用场景</h3>
<ul>
<li>对象间存在一对多关系，一个对象的状态发生改变会影响其他对象。</li>
<li>当一个抽象模型有两个方面，其中一个方面依赖于另一方面时。</li>
</ul>
<h3 id="666-jdk中提供的实现"><a class="markdownIt-Anchor" href="#666-jdk中提供的实现">#</a> 6.6.6 JDK 中提供的实现</h3>
<p>在 Java 中，通过 java.util.Observable 类和 java.util.Observer 接口定义了观察者模式，只要实现它们的子类就可以编写观察者模式实例。</p>
<p><strong>1，Observable 类</strong></p>
<p>Observable 类是抽象目标类（被观察者），它有一个 Vector 集合成员变量，用于保存所有要通知的观察者对象，下面来介绍它最重要的 3 个方法。</p>
<ul>
<li>
<p>void addObserver (Observer o) 方法：用于将新的观察者对象添加到集合中。</p>
</li>
<li>
<p>void notifyObservers (Object arg) 方法：调用集合中的所有观察者对象的 update 方法，通知它们数据发生改变。通常越晚加入集合的观察者越先得到通知。</p>
</li>
<li>
<p>void setChange () 方法：用来设置一个 boolean 类型的内部标志，注明目标对象发生了变化。当它为 true 时，notifyObservers () 才会通知观察者。</p>
</li>
</ul>
<p><strong>2，Observer 接口</strong></p>
<p>Observer 接口是抽象观察者，它监视目标对象的变化，当目标对象发生变化时，观察者得到通知，并调用 update 方法，进行相应的工作。</p>
<p>【例】警察抓小偷</p>
<p>警察抓小偷也可以使用观察者模式来实现，警察是观察者，小偷是被观察者。代码如下：</p>
<p>小偷是一个被观察者，所以需要继承 Observable 类</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Thief</span> <span class="keyword">extends</span> <span class="title class_">Observable</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Thief</span><span class="params">(String name)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setName</span><span class="params">(String name)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getName</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">steal</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;小偷：我偷东西了，有没有人来抓我！！！&quot;</span>);</span><br><span class="line">        <span class="built_in">super</span>.setChanged(); <span class="comment">//changed  = true</span></span><br><span class="line">        <span class="built_in">super</span>.notifyObservers();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure></div>
<p>警察是一个观察者，所以需要让其实现 Observer 接口</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Policemen</span> <span class="keyword">implements</span> <span class="title class_">Observer</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Policemen</span><span class="params">(String name)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setName</span><span class="params">(String name)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getName</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">update</span><span class="params">(Observable o, Object arg)</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;警察：&quot;</span> + ((Thief) o).getName() + <span class="string">&quot;，我已经盯你很久了，你可以保持沉默，但你所说的将成为呈堂证供！！！&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>客户端代码</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Client</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="comment">//创建小偷对象</span></span><br><span class="line">        <span class="type">Thief</span> <span class="variable">t</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Thief</span>(<span class="string">&quot;隔壁老王&quot;</span>);</span><br><span class="line">        <span class="comment">//创建警察对象</span></span><br><span class="line">        <span class="type">Policemen</span> <span class="variable">p</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Policemen</span>(<span class="string">&quot;小李&quot;</span>);</span><br><span class="line">        <span class="comment">//让警察盯着小偷</span></span><br><span class="line">        t.addObserver(p);</span><br><span class="line">        <span class="comment">//小偷偷东西</span></span><br><span class="line">        t.steal();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<h2 id="67-中介者模式"><a class="markdownIt-Anchor" href="#67-中介者模式">#</a> 6.7 中介者模式</h2>
<h3 id="671-概述"><a class="markdownIt-Anchor" href="#671-概述">#</a> 6.7.1 概述</h3>
<p>一般来说，同事类之间的关系是比较复杂的，多个同事类之间互相关联时，他们之间的关系会呈现为复杂的网状结构，这是一种过度耦合的架构，即不利于类的复用，也不稳定。例如在下左图中，有六个同事类对象，假如对象 1 发生变化，那么将会有 4 个对象受到影响。如果对象 2 发生变化，那么将会有 5 个对象受到影响。也就是说，同事类之间直接关联的设计是不好的。</p>
<p>如果引入中介者模式，那么同事类之间的关系将变为星型结构，从下右图中可以看到，任何一个类的变动，只会影响的类本身，以及中介者，这样就减小了系统的耦合。一个好的设计，必定不会把所有的对象关系处理逻辑封装在本类中，而是使用一个专门的类来管理那些不属于自己的行为。</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420232203595.png"
                      alt="在这里插入图片描述"
                ></p>
<p><strong>定义：</strong></p>
<p>又叫调停模式，定义一个中介角色来封装一系列对象之间的交互，使原有对象之间的耦合松散，且可以独立地改变它们之间的交互。</p>
<h3 id="672-结构"><a class="markdownIt-Anchor" href="#672-结构">#</a> 6.7.2 结构</h3>
<p>中介者模式包含以下主要角色：</p>
<ul>
<li>
<p>抽象中介者（Mediator）角色：它是中介者的接口，提供了同事对象注册与转发同事对象信息的抽象方法。</p>
</li>
<li>
<p>具体中介者（ConcreteMediator）角色：实现中介者接口，定义一个 List 来管理同事对象，协调各个同事角色之间的交互关系，因此它依赖于同事角色。</p>
</li>
<li>
<p>抽象同事类（Colleague）角色：定义同事类的接口，保存中介者对象，提供同事对象交互的抽象方法，实现所有相互影响的同事类的公共功能。</p>
</li>
<li>
<p>具体同事类（Concrete Colleague）角色：是抽象同事类的实现者，当需要与其他同事对象交互时，由中介者对象负责后续的交互。</p>
</li>
</ul>
<h3 id="673-案例实现"><a class="markdownIt-Anchor" href="#673-案例实现">#</a> 6.7.3 案例实现</h3>
<p>【例】租房</p>
<p>现在租房基本都是通过房屋中介，房主将房屋托管给房屋中介，而租房者从房屋中介获取房屋信息。房屋中介充当租房者与房屋所有者之间的中介者。</p>
<p>类图如下：<br>
<img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420232240991.png"
                      alt="在这里插入图片描述"
                ></p>
<p>代码如下：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//抽象中介者</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title class_">Mediator</span> &#123;</span><br><span class="line">    <span class="comment">//申明一个联络方法</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title function_">constact</span><span class="params">(String message,Person person)</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//抽象同事类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title class_">Person</span> &#123;</span><br><span class="line">    <span class="keyword">protected</span> String name;</span><br><span class="line">    <span class="keyword">protected</span> Mediator mediator;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Person</span><span class="params">(String name,Mediator mediator)</span>&#123;</span><br><span class="line">        <span class="built_in">this</span>.name = name;</span><br><span class="line">        <span class="built_in">this</span>.mediator = mediator;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//具体同事类 房屋拥有者</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">HouseOwner</span> <span class="keyword">extends</span> <span class="title class_">Person</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">HouseOwner</span><span class="params">(String name, Mediator mediator)</span> &#123;</span><br><span class="line">        <span class="built_in">super</span>(name, mediator);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//与中介者联系</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">constact</span><span class="params">(String message)</span>&#123;</span><br><span class="line">        mediator.constact(message, <span class="built_in">this</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//获取信息</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">getMessage</span><span class="params">(String message)</span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;房主&quot;</span> + name +<span class="string">&quot;获取到的信息：&quot;</span> + message);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//具体同事类 承租人</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Tenant</span> <span class="keyword">extends</span> <span class="title class_">Person</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Tenant</span><span class="params">(String name, Mediator mediator)</span> &#123;</span><br><span class="line">        <span class="built_in">super</span>(name, mediator);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//与中介者联系</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">constact</span><span class="params">(String message)</span>&#123;</span><br><span class="line">        mediator.constact(message, <span class="built_in">this</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//获取信息</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">getMessage</span><span class="params">(String message)</span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;租房者&quot;</span> + name +<span class="string">&quot;获取到的信息：&quot;</span> + message);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//中介机构</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MediatorStructure</span> <span class="keyword">extends</span> <span class="title class_">Mediator</span> &#123;</span><br><span class="line">    <span class="comment">//首先中介结构必须知道所有房主和租房者的信息</span></span><br><span class="line">    <span class="keyword">private</span> HouseOwner houseOwner;</span><br><span class="line">    <span class="keyword">private</span> Tenant tenant;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> HouseOwner <span class="title function_">getHouseOwner</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> houseOwner;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setHouseOwner</span><span class="params">(HouseOwner houseOwner)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.houseOwner = houseOwner;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Tenant <span class="title function_">getTenant</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> tenant;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setTenant</span><span class="params">(Tenant tenant)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.tenant = tenant;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">constact</span><span class="params">(String message, Person person)</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (person == houseOwner) &#123;          <span class="comment">//如果是房主，则租房者获得信息</span></span><br><span class="line">            tenant.getMessage(message);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;       <span class="comment">//反正则是房主获得信息</span></span><br><span class="line">            houseOwner.getMessage(message);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//测试类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Client</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="comment">//一个房主、一个租房者、一个中介机构</span></span><br><span class="line">        <span class="type">MediatorStructure</span> <span class="variable">mediator</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">MediatorStructure</span>();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//房主和租房者只需要知道中介机构即可</span></span><br><span class="line">        <span class="type">HouseOwner</span> <span class="variable">houseOwner</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">HouseOwner</span>(<span class="string">&quot;张三&quot;</span>, mediator);</span><br><span class="line">        <span class="type">Tenant</span> <span class="variable">tenant</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Tenant</span>(<span class="string">&quot;李四&quot;</span>, mediator);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//中介结构要知道房主和租房者</span></span><br><span class="line">        mediator.setHouseOwner(houseOwner);</span><br><span class="line">        mediator.setTenant(tenant);</span><br><span class="line"></span><br><span class="line">        tenant.constact(<span class="string">&quot;需要租三室的房子&quot;</span>);</span><br><span class="line">        houseOwner.constact(<span class="string">&quot;我这有三室的房子，你需要租吗？&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<h3 id="674-优缺点"><a class="markdownIt-Anchor" href="#674-优缺点">#</a> 6.7.4 优缺点</h3>
<p><strong>1，优点：</strong></p>
<ul>
<li>
<p>松散耦合</p>
<p>中介者模式通过把多个同事对象之间的交互封装到中介者对象里面，从而使得同事对象之间松散耦合，基本上可以做到互补依赖。这样一来，同事对象就可以独立地变化和复用，而不再像以前那样 “牵一处而动全身” 了。</p>
</li>
<li>
<p>集中控制交互</p>
<p>多个同事对象的交互，被封装在中介者对象里面集中管理，使得这些交互行为发生变化的时候，只需要修改中介者对象就可以了，当然如果是已经做好的系统，那么就扩展中介者对象，而各个同事类不需要做修改。</p>
</li>
<li>
<p>一对多关联转变为一对一的关联</p>
<p>没有使用中介者模式的时候，同事对象之间的关系通常是一对多的，引入中介者对象以后，中介者对象和同事对象的关系通常变成双向的一对一，这会让对象的关系更容易理解和实现。</p>
</li>
</ul>
<p><strong>2，缺点：</strong></p>
<p>当同事类太多时，中介者的职责将很大，它会变得复杂而庞大，以至于系统难以维护。</p>
<h3 id="675-使用场景"><a class="markdownIt-Anchor" href="#675-使用场景">#</a> 6.7.5 使用场景</h3>
<ul>
<li>系统中对象之间存在复杂的引用关系，系统结构混乱且难以理解。</li>
<li>当想创建一个运行于多个类之间的对象，又不想生成新的子类时。</li>
</ul>
<h2 id="68-迭代器模式"><a class="markdownIt-Anchor" href="#68-迭代器模式">#</a> 6.8 迭代器模式</h2>
<h3 id="681-概述"><a class="markdownIt-Anchor" href="#681-概述">#</a> 6.8.1 概述</h3>
<p><strong>定义：</strong></p>
<p>提供一个对象来顺序访问聚合对象中的一系列数据，而不暴露聚合对象的内部表示。</p>
<h3 id="682-结构"><a class="markdownIt-Anchor" href="#682-结构">#</a> 6.8.2 结构</h3>
<p>迭代器模式主要包含以下角色：</p>
<ul>
<li>
<p>抽象聚合（Aggregate）角色：定义存储、添加、删除聚合元素以及创建迭代器对象的接口。</p>
</li>
<li>
<p>具体聚合（ConcreteAggregate）角色：实现抽象聚合类，返回一个具体迭代器的实例。</p>
</li>
<li>
<p>抽象迭代器（Iterator）角色：定义访问和遍历聚合元素的接口，通常包含 hasNext ()、next () 等方法。</p>
</li>
<li>
<p>具体迭代器（Concretelterator）角色：实现抽象迭代器接口中所定义的方法，完成对聚合对象的遍历，记录遍历的当前位置。</p>
</li>
</ul>
<h3 id="683-案例实现"><a class="markdownIt-Anchor" href="#683-案例实现">#</a> 6.8.3 案例实现</h3>
<p>【例】定义一个可以存储学生对象的容器对象，将遍历该容器的功能交由迭代器实现，涉及到的类如下：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420232317504.png"
                      alt="在这里插入图片描述"
                ></p>
<p>代码如下：</p>
<p>定义迭代器接口，声明 hasNext、next 方法</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">StudentIterator</span> &#123;</span><br><span class="line">    <span class="type">boolean</span> <span class="title function_">hasNext</span><span class="params">()</span>;</span><br><span class="line">    Student <span class="title function_">next</span><span class="params">()</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>定义具体的迭代器类，重写所有的抽象方法</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">StudentIteratorImpl</span> <span class="keyword">implements</span> <span class="title class_">StudentIterator</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> List&lt;Student&gt; list;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> <span class="variable">position</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">StudentIteratorImpl</span><span class="params">(List&lt;Student&gt; list)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.list = list;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="type">boolean</span> <span class="title function_">hasNext</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> position &lt; list.size();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> Student <span class="title function_">next</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">Student</span> <span class="variable">currentStudent</span> <span class="operator">=</span> list.get(position);</span><br><span class="line">        position ++;</span><br><span class="line">        <span class="keyword">return</span> currentStudent;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>定义抽象容器类，包含添加元素，删除元素，获取迭代器对象的方法</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">StudentAggregate</span> &#123;</span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">addStudent</span><span class="params">(Student student)</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">removeStudent</span><span class="params">(Student student)</span>;</span><br><span class="line"></span><br><span class="line">    StudentIterator <span class="title function_">getStudentIterator</span><span class="params">()</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>定义具体的容器类，重写所有的方法</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">StudentAggregateImpl</span> <span class="keyword">implements</span> <span class="title class_">StudentAggregate</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> List&lt;Student&gt; list = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;Student&gt;();  <span class="comment">// 学生列表</span></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">addStudent</span><span class="params">(Student student)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.list.add(student);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">removeStudent</span><span class="params">(Student student)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.list.remove(student);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> StudentIterator <span class="title function_">getStudentIterator</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">StudentIteratorImpl</span>(list);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<h3 id="684-优缺点"><a class="markdownIt-Anchor" href="#684-优缺点">#</a> 6.8.4 优缺点</h3>
<p><strong>1，优点：</strong></p>
<ul>
<li>它支持以不同的方式遍历一个聚合对象，在同一个聚合对象上可以定义多种遍历方式。在迭代器模式中只需要用一个不同的迭代器来替换原有迭代器即可改变遍历算法，我们也可以自己定义迭代器的子类以支持新的遍历方式。</li>
<li>迭代器简化了聚合类。由于引入了迭代器，在原有的聚合对象中不需要再自行提供数据遍历等方法，这样可以简化聚合类的设计。</li>
<li>在迭代器模式中，由于引入了抽象层，增加新的聚合类和迭代器类都很方便，无须修改原有代码，满足 “开闭原则” 的要求。</li>
</ul>
<p><strong>2，缺点：</strong></p>
<p>增加了类的个数，这在一定程度上增加了系统的复杂性。</p>
<h3 id="685-使用场景"><a class="markdownIt-Anchor" href="#685-使用场景">#</a> 6.8.5 使用场景</h3>
<ul>
<li>当需要为聚合对象提供多种遍历方式时。</li>
<li>当需要为遍历不同的聚合结构提供一个统一的接口时。</li>
<li>当访问一个聚合对象的内容而无须暴露其内部细节的表示时。</li>
</ul>
<h3 id="686-jdk源码解析"><a class="markdownIt-Anchor" href="#686-jdk源码解析">#</a> 6.8.6 JDK 源码解析</h3>
<p>迭代器模式在 JAVA 的很多集合类中被广泛应用，接下来看看 JAVA 源码中是如何使用迭代器模式的。</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">List&lt;String&gt; list = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;&gt;();</span><br><span class="line">Iterator&lt;String&gt; iterator = list.iterator(); <span class="comment">//list.iterator()方法返回的肯定是Iterator接口的子实现类对象</span></span><br><span class="line"><span class="keyword">while</span> (iterator.hasNext()) &#123;</span><br><span class="line">    System.out.println(iterator.next());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>看完这段代码是不是很熟悉，与我们上面代码基本类似。单列集合都使用到了迭代器，我们以 ArrayList 举例来说明</p>
<ul>
<li>List：抽象聚合类</li>
<li>ArrayList：具体的聚合类</li>
<li>Iterator：抽象迭代器</li>
<li>list.iterator ()：返回的是实现了  <code>Iterator</code>  接口的具体迭代器对象</li>
</ul>
<p>具体的来看看 ArrayList 的代码实现</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ArrayList</span>&lt;E&gt; <span class="keyword">extends</span> <span class="title class_">AbstractList</span>&lt;E&gt;</span><br><span class="line">        <span class="keyword">implements</span> <span class="title class_">List</span>&lt;E&gt;, RandomAccess, Cloneable, java.io.Serializable &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">public</span> Iterator&lt;E&gt; <span class="title function_">iterator</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Itr</span>();</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">class</span> <span class="title class_">Itr</span> <span class="keyword">implements</span> <span class="title class_">Iterator</span>&lt;E&gt; &#123;</span><br><span class="line">        <span class="type">int</span> cursor;       <span class="comment">// 下一个要返回元素的索引</span></span><br><span class="line">        <span class="type">int</span> <span class="variable">lastRet</span> <span class="operator">=</span> -<span class="number">1</span>; <span class="comment">// 上一个返回元素的索引</span></span><br><span class="line">        <span class="type">int</span> <span class="variable">expectedModCount</span> <span class="operator">=</span> modCount;</span><br><span class="line"></span><br><span class="line">        Itr() &#123;&#125;</span><br><span class="line">		</span><br><span class="line">        <span class="comment">//判断是否还有元素</span></span><br><span class="line">        <span class="keyword">public</span> <span class="type">boolean</span> <span class="title function_">hasNext</span><span class="params">()</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> cursor != size;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//获取下一个元素</span></span><br><span class="line">        <span class="keyword">public</span> E <span class="title function_">next</span><span class="params">()</span> &#123;</span><br><span class="line">            checkForComodification();</span><br><span class="line">            <span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> cursor;</span><br><span class="line">            <span class="keyword">if</span> (i &gt;= size)</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">NoSuchElementException</span>();</span><br><span class="line">            Object[] elementData = ArrayList.<span class="built_in">this</span>.elementData;</span><br><span class="line">            <span class="keyword">if</span> (i &gt;= elementData.length)</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">ConcurrentModificationException</span>();</span><br><span class="line">            cursor = i + <span class="number">1</span>;</span><br><span class="line">            <span class="keyword">return</span> (E) elementData[lastRet = i];</span><br><span class="line">        &#125;</span><br><span class="line">        ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>这部分代码还是比较简单，大致就是在  <code>iterator</code>  方法中返回了一个实例化的  <code>Iterator</code>  对象。Itr 是一个内部类，它实现了  <code>Iterator</code>  接口并重写了其中的抽象方法。</p>
<blockquote>
<p>注意：</p>
<p>当我们在使用 JAVA 开发的时候，想使用迭代器模式的话，只要让我们自己定义的容器类实现 <code>java.util.Iterable</code>  并实现其中的 iterator () 方法使其返回一个  <code>java.util.Iterator</code>  的实现类就可以了。</p>
</blockquote>
<h2 id="69-访问者模式"><a class="markdownIt-Anchor" href="#69-访问者模式">#</a> 6.9 访问者模式</h2>
<h3 id="691-概述"><a class="markdownIt-Anchor" href="#691-概述">#</a> 6.9.1 概述</h3>
<p><strong>定义：</strong></p>
<p>封装一些作用于某种数据结构中的各元素的操作，它可以在不改变这个数据结构的前提下定义作用于这些元素的新的操作。</p>
<h3 id="692-结构"><a class="markdownIt-Anchor" href="#692-结构">#</a> 6.9.2 结构</h3>
<p>访问者模式包含以下主要角色:</p>
<ul>
<li>抽象访问者（Visitor）角色：定义了对每一个元素 <code>（Element）</code> 访问的行为，它的参数就是可以访问的元素，它的方法个数理论上来讲与元素类个数（Element 的实现类个数）是一样的，从这点不难看出，访问者模式要求元素类的个数不能改变。</li>
<li>具体访问者（ConcreteVisitor）角色：给出对每一个元素类访问时所产生的具体行为。</li>
<li>抽象元素（Element）角色：定义了一个接受访问者的方法（ <code>accept</code> ），其意义是指，每一个元素都要可以被访问者访问。</li>
<li>具体元素（ConcreteElement）角色： 提供接受访问方法的具体实现，而这个具体的实现，通常情况下是使用访问者提供的访问该元素类的方法。</li>
<li>对象结构（Object Structure）角色：定义当中所提到的对象结构，对象结构是一个抽象表述，具体点可以理解为一个具有容器性质或者复合对象特性的类，它会含有一组元素（ <code>Element</code> ），并且可以迭代这些元素，供访问者访问。</li>
</ul>
<h3 id="693-案例实现"><a class="markdownIt-Anchor" href="#693-案例实现">#</a> 6.9.3 案例实现</h3>
<p>【例】给宠物喂食</p>
<p>现在养宠物的人特别多，我们就以这个为例，当然宠物还分为狗，猫等，要给宠物喂食的话，主人可以喂，其他人也可以喂食。</p>
<ul>
<li>访问者角色：给宠物喂食的人</li>
<li>具体访问者角色：主人、其他人</li>
<li>抽象元素角色：动物抽象类</li>
<li>具体元素角色：宠物狗、宠物猫</li>
<li>结构对象角色：主人家</li>
</ul>
<p>类图如下：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420225744449.png"
                      alt="在这里插入图片描述"
                ></p>
<p>代码如下：</p>
<p>创建抽象访问者接口</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">Person</span> &#123;</span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">feed</span><span class="params">(Cat cat)</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">feed</span><span class="params">(Dog dog)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>创建不同的具体访问者角色（主人和其他人），都需要实现  <code>Person</code>  接口</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Owner</span> <span class="keyword">implements</span> <span class="title class_">Person</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">feed</span><span class="params">(Cat cat)</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;主人喂食猫&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">feed</span><span class="params">(Dog dog)</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;主人喂食狗&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Someone</span> <span class="keyword">implements</span> <span class="title class_">Person</span> &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">feed</span><span class="params">(Cat cat)</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;其他人喂食猫&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">feed</span><span class="params">(Dog dog)</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;其他人喂食狗&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>定义抽象节点 – 宠物</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">Animal</span> &#123;</span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">accept</span><span class="params">(Person person)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>定义实现 <code>Animal</code>  接口的 具体节点（元素）</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Dog</span> <span class="keyword">implements</span> <span class="title class_">Animal</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">accept</span><span class="params">(Person person)</span> &#123;</span><br><span class="line">        person.feed(<span class="built_in">this</span>);</span><br><span class="line">        System.out.println(<span class="string">&quot;好好吃，汪汪汪！！！&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Cat</span> <span class="keyword">implements</span> <span class="title class_">Animal</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">accept</span><span class="params">(Person person)</span> &#123;</span><br><span class="line">        person.feed(<span class="built_in">this</span>);</span><br><span class="line">        System.out.println(<span class="string">&quot;好好吃，喵喵喵！！！&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>定义对象结构，此案例中就是主人的家</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Home</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> List&lt;Animal&gt; nodeList = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;Animal&gt;();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">action</span><span class="params">(Person person)</span> &#123;</span><br><span class="line">        <span class="keyword">for</span> (Animal node : nodeList) &#123;</span><br><span class="line">            node.accept(person);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//添加操作</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">add</span><span class="params">(Animal animal)</span> &#123;</span><br><span class="line">        nodeList.add(animal);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure></div>
<p>测试类</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Client</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">Home</span> <span class="variable">home</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Home</span>();</span><br><span class="line">        home.add(<span class="keyword">new</span> <span class="title class_">Dog</span>());</span><br><span class="line">        home.add(<span class="keyword">new</span> <span class="title class_">Cat</span>());</span><br><span class="line"></span><br><span class="line">        <span class="type">Owner</span> <span class="variable">owner</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Owner</span>();</span><br><span class="line">        home.action(owner);</span><br><span class="line"></span><br><span class="line">        <span class="type">Someone</span> <span class="variable">someone</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Someone</span>();</span><br><span class="line">        home.action(someone);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<h3 id="694-优缺点"><a class="markdownIt-Anchor" href="#694-优缺点">#</a> 6.9.4 优缺点</h3>
<p><strong>1，优点：</strong></p>
<ul>
<li>
<p>扩展性好</p>
<p>在不修改对象结构中的元素的情况下，为对象结构中的元素添加新的功能。</p>
</li>
<li>
<p>复用性好</p>
<p>通过访问者来定义整个对象结构通用的功能，从而提高复用程度。</p>
</li>
<li>
<p>分离无关行为</p>
<p>通过访问者来分离无关的行为，把相关的行为封装在一起，构成一个访问者，这样每一个访问者的功能都比较单一。</p>
</li>
</ul>
<p><strong>2，缺点：</strong></p>
<ul>
<li>
<p>对象结构变化很困难</p>
<p>在访问者模式中，每增加一个新的元素类，都要在每一个具体访问者类中增加相应的具体操作，这违背了 “开闭原则”。</p>
</li>
<li>
<p>违反了依赖倒置原则</p>
<p>访问者模式依赖了具体类，而没有依赖抽象类。</p>
</li>
</ul>
<h3 id="695-使用场景"><a class="markdownIt-Anchor" href="#695-使用场景">#</a> 6.9.5  使用场景</h3>
<ul>
<li>
<p>对象结构相对稳定，但其操作算法经常变化的程序。</p>
</li>
<li>
<p>对象结构中的对象需要提供多种不同且不相关的操作，而且要避免让这些操作的变化影响对象的结构。</p>
</li>
</ul>
<h3 id="696-扩展"><a class="markdownIt-Anchor" href="#696-扩展">#</a> 6.9.6 扩展</h3>
<p>访问者模式用到了一种双分派的技术。</p>
<p><strong>1，分派：</strong></p>
<p>变量被声明时的类型叫做变量的静态类型，有些人又把静态类型叫做明显类型；而变量所引用的对象的真实类型又叫做变量的实际类型。比如  <code>Map map = new HashMap()</code>  ，map 变量的静态类型是  <code>Map</code>  ，实际类型是  <code>HashMap</code>  。根据对象的类型而对方法进行的选择，就是分派 (Dispatch)，分派 (Dispatch) 又分为两种，即静态分派和动态分派。</p>
<p><strong>静态分派 (Static Dispatch)</strong> 发生在编译时期，分派根据静态类型信息发生。静态分派对于我们来说并不陌生，方法重载就是静态分派。</p>
<p><strong>动态分派 (Dynamic Dispatch)</strong> 发生在运行时期，动态分派动态地置换掉某个方法。Java 通过方法的重写支持动态分派。</p>
<p><strong>2，动态分派：</strong></p>
<p>通过方法的重写支持动态分派。</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Animal</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">execute</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;Animal&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Dog</span> <span class="keyword">extends</span> <span class="title class_">Animal</span> &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">execute</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;dog&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Cat</span> <span class="keyword">extends</span> <span class="title class_">Animal</span> &#123;</span><br><span class="line">     <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">execute</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;cat&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Client</span> &#123;</span><br><span class="line">   	<span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">Animal</span> <span class="variable">a</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Dog</span>();</span><br><span class="line">        a.execute();</span><br><span class="line">        </span><br><span class="line">        <span class="type">Animal</span> <span class="variable">a1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Cat</span>();</span><br><span class="line">        a1.execute();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>上面代码的结果大家应该直接可以说出来，这不就是多态吗！运行执行的是子类中的方法。</p>
<p>Java 编译器在编译时期并不总是知道哪些代码会被执行，因为编译器仅仅知道对象的静态类型，而不知道对象的真实类型；而方法的调用则是根据对象的真实类型，而不是静态类型。</p>
<p><strong>3，静态分派：</strong></p>
<p>通过方法重载支持静态分派。</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Animal</span> &#123;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Dog</span> <span class="keyword">extends</span> <span class="title class_">Animal</span> &#123;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Cat</span> <span class="keyword">extends</span> <span class="title class_">Animal</span> &#123;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Execute</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">execute</span><span class="params">(Animal a)</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;Animal&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">execute</span><span class="params">(Dog d)</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;dog&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">execute</span><span class="params">(Cat c)</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;cat&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Client</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">Animal</span> <span class="variable">a</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Animal</span>();</span><br><span class="line">        <span class="type">Animal</span> <span class="variable">a1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Dog</span>();</span><br><span class="line">        <span class="type">Animal</span> <span class="variable">a2</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Cat</span>();</span><br><span class="line"></span><br><span class="line">        <span class="type">Execute</span> <span class="variable">exe</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Execute</span>();</span><br><span class="line">        exe.execute(a);</span><br><span class="line">        exe.execute(a1);</span><br><span class="line">        exe.execute(a2);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>运行结果：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420232437613.png"
                      alt="在这里插入图片描述"
                ></p>
<p>这个结果可能出乎一些人的意料了，为什么呢？</p>
<p><strong>重载方法的分派是根据静态类型进行的，这个分派过程在编译时期就完成了。</strong></p>
<p><strong>4，双分派：</strong></p>
<p>所谓双分派技术就是在选择一个方法的时候，不仅仅要根据消息接收者（receiver）的运行时区别，还要根据参数的运行时区别。</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Animal</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">accept</span><span class="params">(Execute exe)</span> &#123;</span><br><span class="line">        exe.execute(<span class="built_in">this</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Dog</span> <span class="keyword">extends</span> <span class="title class_">Animal</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">accept</span><span class="params">(Execute exe)</span> &#123;</span><br><span class="line">        exe.execute(<span class="built_in">this</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Cat</span> <span class="keyword">extends</span> <span class="title class_">Animal</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">accept</span><span class="params">(Execute exe)</span> &#123;</span><br><span class="line">        exe.execute(<span class="built_in">this</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Execute</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">execute</span><span class="params">(Animal a)</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;animal&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">execute</span><span class="params">(Dog d)</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;dog&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">execute</span><span class="params">(Cat c)</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;cat&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Client</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">Animal</span> <span class="variable">a</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Animal</span>();</span><br><span class="line">        <span class="type">Animal</span> <span class="variable">d</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Dog</span>();</span><br><span class="line">        <span class="type">Animal</span> <span class="variable">c</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Cat</span>();</span><br><span class="line"></span><br><span class="line">        <span class="type">Execute</span> <span class="variable">exe</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Execute</span>();</span><br><span class="line">        a.accept(exe);</span><br><span class="line">        d.accept(exe);</span><br><span class="line">        c.accept(exe);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>在上面代码中，客户端将 Execute 对象做为参数传递给 Animal 类型的变量调用的方法，这里完成第一次分派，这里是方法重写，所以是动态分派，也就是执行实际类型中的方法，同时也 <code>将自己this作为参数传递进去，这里就完成了第二次分派</code> ，这里的 Execute 类中有多个重载的方法，而传递进行的是 this，就是具体的实际类型的对象。</p>
<p>说到这里，我们已经明白双分派是怎么回事了，但是它有什么效果呢？就是可以实现方法的动态绑定，我们可以对上面的程序进行修改。</p>
<p>运行结果如下：<br>
<img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420232505144.png"
                      alt="在这里插入图片描述"
                ></p>
<p><strong>双分派实现动态绑定的本质，就是在重载方法委派的前面加上了继承体系中覆盖的环节，由于覆盖是动态的，所以重载就是动态的了。</strong></p>
<h2 id="610-备忘录模式"><a class="markdownIt-Anchor" href="#610-备忘录模式">#</a> 6.10 备忘录模式</h2>
<h3 id="6101-概述"><a class="markdownIt-Anchor" href="#6101-概述">#</a> 6.10.1 概述</h3>
<p>备忘录模式提供了一种状态恢复的实现机制，使得用户可以方便地回到一个特定的历史步骤，当新的状态无效或者存在问题时，可以使用暂时存储起来的备忘录将状态复原，很多软件都提供了撤销（Undo）操作，如 Word、记事本、Photoshop、IDEA 等软件在编辑时按 Ctrl+Z 组合键时能撤销当前操作，使文档恢复到之前的状态；还有在 浏览器 中的后退键、数据库事务管理中的回滚操作、玩游戏时的中间结果存档功能、数据库与操作系统的备份操作、棋类游戏中的悔棋功能等都属于这类。</p>
<p><strong>定义：</strong></p>
<p>又叫快照模式，在不破坏封装性的前提下，捕获一个对象的内部状态，并在该对象之外保存这个状态，以便以后当需要时能将该对象恢复到原先保存的状态。</p>
<h3 id="6102-结构"><a class="markdownIt-Anchor" href="#6102-结构">#</a> 6.10.2 结构</h3>
<p>备忘录模式的主要角色如下：</p>
<ul>
<li>发起人（Originator）角色：记录当前时刻的内部状态信息，提供创建备忘录和恢复备忘录数据的功能，实现其他业务功能，它可以访问备忘录里的所有信息。</li>
<li>备忘录（Memento）角色：负责存储发起人的内部状态，在需要的时候提供这些内部状态给发起人。</li>
<li>管理者（Caretaker）角色：对备忘录进行管理，提供保存与获取备忘录的功能，但其不能对备忘录的内容进行访问与修改。</li>
</ul>
<blockquote>
<p>备忘录有两个等效的接口：</p>
<ul>
<li><strong>窄接口</strong>：管理者 (Caretaker) 对象（和其他发起人对象之外的任何对象）看到的是备忘录的窄接口 (narror Interface)，这个窄接口只允许他把备忘录对象传给其他的对象。</li>
<li><strong>宽接口</strong>：与管理者看到的窄接口相反，发起人对象可以看到一个宽接口 (wide Interface)，这个宽接口允许它读取所有的数据，以便根据这些数据恢复这个发起人对象的内部状态。</li>
</ul>
</blockquote>
<h3 id="6103-案例实现"><a class="markdownIt-Anchor" href="#6103-案例实现">#</a> 6.10.3 案例实现</h3>
<p>【例】游戏挑战 BOSS</p>
<p>游戏中的某个场景，一游戏角色有生命力、攻击力、防御力等数据，在打 Boss 前和后一定会不一样的，我们允许玩家如果感觉与 Boss 决斗的效果不理想可以让游戏恢复到决斗之前的状态。</p>
<p>要实现上述案例，有两种方式：</p>
<ul>
<li>“白箱” 备忘录模式</li>
<li>“黑箱” 备忘录模式</li>
</ul>
<h4 id="61031-白箱备忘录模式"><a class="markdownIt-Anchor" href="#61031-白箱备忘录模式">#</a> 6.10.3.1 “白箱” 备忘录模式</h4>
<p>备忘录角色对任何对象都提供一个接口，即宽接口，备忘录角色的内部所存储的状态就对所有对象公开。类图如下：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420232536766.png"
                      alt="在这里插入图片描述"
                ></p>
<p>代码如下：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//游戏角色类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">GameRole</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> vit; <span class="comment">//生命力</span></span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> atk; <span class="comment">//攻击力</span></span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> def; <span class="comment">//防御力</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">//初始化状态</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">initState</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.vit = <span class="number">100</span>;</span><br><span class="line">        <span class="built_in">this</span>.atk = <span class="number">100</span>;</span><br><span class="line">        <span class="built_in">this</span>.def = <span class="number">100</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//战斗</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">fight</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.vit = <span class="number">0</span>;</span><br><span class="line">        <span class="built_in">this</span>.atk = <span class="number">0</span>;</span><br><span class="line">        <span class="built_in">this</span>.def = <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//保存角色状态</span></span><br><span class="line">    <span class="keyword">public</span> RoleStateMemento <span class="title function_">saveState</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">RoleStateMemento</span>(vit, atk, def);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//回复角色状态</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">recoverState</span><span class="params">(RoleStateMemento roleStateMemento)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.vit = roleStateMemento.getVit();</span><br><span class="line">        <span class="built_in">this</span>.atk = roleStateMemento.getAtk();</span><br><span class="line">        <span class="built_in">this</span>.def = roleStateMemento.getDef();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">stateDisplay</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;角色生命力：&quot;</span> + vit);</span><br><span class="line">        System.out.println(<span class="string">&quot;角色攻击力：&quot;</span> + atk);</span><br><span class="line">        System.out.println(<span class="string">&quot;角色防御力：&quot;</span> + def);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">getVit</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> vit;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setVit</span><span class="params">(<span class="type">int</span> vit)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.vit = vit;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">getAtk</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> atk;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setAtk</span><span class="params">(<span class="type">int</span> atk)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.atk = atk;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">getDef</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> def;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setDef</span><span class="params">(<span class="type">int</span> def)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.def = def;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//游戏状态存储类(备忘录类)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">RoleStateMemento</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> vit;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> atk;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> def;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">RoleStateMemento</span><span class="params">(<span class="type">int</span> vit, <span class="type">int</span> atk, <span class="type">int</span> def)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.vit = vit;</span><br><span class="line">        <span class="built_in">this</span>.atk = atk;</span><br><span class="line">        <span class="built_in">this</span>.def = def;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">getVit</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> vit;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setVit</span><span class="params">(<span class="type">int</span> vit)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.vit = vit;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">getAtk</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> atk;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setAtk</span><span class="params">(<span class="type">int</span> atk)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.atk = atk;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">getDef</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> def;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setDef</span><span class="params">(<span class="type">int</span> def)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.def = def;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//角色状态管理者类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">RoleStateCaretaker</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> RoleStateMemento roleStateMemento;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> RoleStateMemento <span class="title function_">getRoleStateMemento</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> roleStateMemento;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setRoleStateMemento</span><span class="params">(RoleStateMemento roleStateMemento)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.roleStateMemento = roleStateMemento;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//测试类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Client</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;------------大战Boss前------------&quot;</span>);</span><br><span class="line">        <span class="comment">//大战Boss前</span></span><br><span class="line">        <span class="type">GameRole</span> <span class="variable">gameRole</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">GameRole</span>();</span><br><span class="line">        gameRole.initState();</span><br><span class="line">        gameRole.stateDisplay();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//保存进度</span></span><br><span class="line">        <span class="type">RoleStateCaretaker</span> <span class="variable">roleStateCaretaker</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">RoleStateCaretaker</span>();</span><br><span class="line">        roleStateCaretaker.setRoleStateMemento(gameRole.saveState());</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;------------大战Boss后------------&quot;</span>);</span><br><span class="line">        <span class="comment">//大战Boss时，损耗严重</span></span><br><span class="line">        gameRole.fight();</span><br><span class="line">        gameRole.stateDisplay();</span><br><span class="line">        System.out.println(<span class="string">&quot;------------恢复之前状态------------&quot;</span>);</span><br><span class="line">        <span class="comment">//恢复之前状态</span></span><br><span class="line">        gameRole.recoverState(roleStateCaretaker.getRoleStateMemento());</span><br><span class="line">        gameRole.stateDisplay();</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<blockquote>
<p>分析：白箱备忘录模式是破坏封装性的。但是通过程序员自律，同样可以在一定程度上实现模式的大部分用意。</p>
</blockquote>
<h4 id="61032-黑箱备忘录模式"><a class="markdownIt-Anchor" href="#61032-黑箱备忘录模式">#</a> 6.10.3.2 “黑箱” 备忘录模式</h4>
<p>备忘录角色对发起人对象提供一个宽接口，而为其他对象提供一个窄接口。在 Java 语言中，实现双重接口的办法就是将<strong>备忘录类</strong>设计成<strong>发起人类</strong>的内部成员类。</p>
<p>将  <code>RoleStateMemento</code>  设为  <code>GameRole</code>  的内部类，从而将  <code>RoleStateMemento</code>  对象封装在  <code>GameRole</code>  里面；在外面提供一个标识接口  <code>Memento</code>  给  <code>RoleStateCaretaker</code>  及其他对象使用。这样  <code>GameRole</code>  类看到的是  <code>RoleStateMemento</code>  所有的接口，而 <code>RoleStateCaretaker</code>   及其他对象看到的仅仅是标识接口  <code>Memento</code>  所暴露出来的接口，从而维护了封装型。类图如下：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420232553228.png"
                      alt="在这里插入图片描述"
                ></p>
<p>代码如下：</p>
<p>窄接口 <code>Memento</code> ，这是一个标识接口，因此没有定义出任何的方法</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">Memento</span> &#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>定义发起人类  <code>GameRole</code> ，并在内部定义备忘录内部类  <code>RoleStateMemento</code> （该内部类设置为私有的）</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br></pre></td><td class="code"><pre><span class="line">/游戏角色类</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">GameRole</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> vit; <span class="comment">//生命力</span></span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> atk; <span class="comment">//攻击力</span></span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> def; <span class="comment">//防御力</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">//初始化状态</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">initState</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.vit = <span class="number">100</span>;</span><br><span class="line">        <span class="built_in">this</span>.atk = <span class="number">100</span>;</span><br><span class="line">        <span class="built_in">this</span>.def = <span class="number">100</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//战斗</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">fight</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.vit = <span class="number">0</span>;</span><br><span class="line">        <span class="built_in">this</span>.atk = <span class="number">0</span>;</span><br><span class="line">        <span class="built_in">this</span>.def = <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//保存角色状态</span></span><br><span class="line">    <span class="keyword">public</span> Memento <span class="title function_">saveState</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">RoleStateMemento</span>(vit, atk, def);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//回复角色状态</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">recoverState</span><span class="params">(Memento memento)</span> &#123;</span><br><span class="line">        <span class="type">RoleStateMemento</span> <span class="variable">roleStateMemento</span> <span class="operator">=</span> (RoleStateMemento) memento;</span><br><span class="line">        <span class="built_in">this</span>.vit = roleStateMemento.getVit();</span><br><span class="line">        <span class="built_in">this</span>.atk = roleStateMemento.getAtk();</span><br><span class="line">        <span class="built_in">this</span>.def = roleStateMemento.getDef();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">stateDisplay</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;角色生命力：&quot;</span> + vit);</span><br><span class="line">        System.out.println(<span class="string">&quot;角色攻击力：&quot;</span> + atk);</span><br><span class="line">        System.out.println(<span class="string">&quot;角色防御力：&quot;</span> + def);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">getVit</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> vit;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setVit</span><span class="params">(<span class="type">int</span> vit)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.vit = vit;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">getAtk</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> atk;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setAtk</span><span class="params">(<span class="type">int</span> atk)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.atk = atk;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">getDef</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> def;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setDef</span><span class="params">(<span class="type">int</span> def)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.def = def;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">class</span> <span class="title class_">RoleStateMemento</span> <span class="keyword">implements</span> <span class="title class_">Memento</span> &#123;</span><br><span class="line">        <span class="keyword">private</span> <span class="type">int</span> vit;</span><br><span class="line">        <span class="keyword">private</span> <span class="type">int</span> atk;</span><br><span class="line">        <span class="keyword">private</span> <span class="type">int</span> def;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">public</span> <span class="title function_">RoleStateMemento</span><span class="params">(<span class="type">int</span> vit, <span class="type">int</span> atk, <span class="type">int</span> def)</span> &#123;</span><br><span class="line">            <span class="built_in">this</span>.vit = vit;</span><br><span class="line">            <span class="built_in">this</span>.atk = atk;</span><br><span class="line">            <span class="built_in">this</span>.def = def;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">getVit</span><span class="params">()</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> vit;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setVit</span><span class="params">(<span class="type">int</span> vit)</span> &#123;</span><br><span class="line">            <span class="built_in">this</span>.vit = vit;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">getAtk</span><span class="params">()</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> atk;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setAtk</span><span class="params">(<span class="type">int</span> atk)</span> &#123;</span><br><span class="line">            <span class="built_in">this</span>.atk = atk;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">getDef</span><span class="params">()</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> def;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setDef</span><span class="params">(<span class="type">int</span> def)</span> &#123;</span><br><span class="line">            <span class="built_in">this</span>.def = def;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>负责人角色类  <code>RoleStateCaretaker</code>  能够得到的备忘录对象是以  <code>Memento</code>  为接口的，由于这个接口仅仅是一个标识接口，因此负责人角色不可能改变这个备忘录对象的内容</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//角色状态管理者类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">RoleStateCaretaker</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> Memento memento;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Memento <span class="title function_">getMemento</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> memento;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setMemento</span><span class="params">(Memento memento)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.memento = memento;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>客户端测试类</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Client</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;------------大战Boss前------------&quot;</span>);</span><br><span class="line">        <span class="comment">//大战Boss前</span></span><br><span class="line">        <span class="type">GameRole</span> <span class="variable">gameRole</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">GameRole</span>();</span><br><span class="line">        gameRole.initState();</span><br><span class="line">        gameRole.stateDisplay();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//保存进度</span></span><br><span class="line">        <span class="type">RoleStateCaretaker</span> <span class="variable">roleStateCaretaker</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">RoleStateCaretaker</span>();</span><br><span class="line">        roleStateCaretaker.setMemento(gameRole.saveState());</span><br><span class="line">        </span><br><span class="line">        System.out.println(<span class="string">&quot;------------大战Boss后------------&quot;</span>);</span><br><span class="line">        <span class="comment">//大战Boss时，损耗严重</span></span><br><span class="line">        gameRole.fight();</span><br><span class="line">        gameRole.stateDisplay();</span><br><span class="line">        System.out.println(<span class="string">&quot;------------恢复之前状态------------&quot;</span>);</span><br><span class="line">        <span class="comment">//恢复之前状态</span></span><br><span class="line">        gameRole.recoverState(roleStateCaretaker.getMemento());</span><br><span class="line">        gameRole.stateDisplay();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure></div>
<h3 id="6104-优缺点"><a class="markdownIt-Anchor" href="#6104-优缺点">#</a> 6.10.4 优缺点</h3>
<p><strong>1，优点：</strong></p>
<ul>
<li>提供了一种可以恢复状态的机制。当用户需要时能够比较方便地将数据恢复到某个历史的状态。</li>
<li>实现了内部状态的封装。除了创建它的发起人之外，其他对象都不能够访问这些状态信息。</li>
<li>简化了发起人类。发起人不需要管理和保存其内部状态的各个备份，所有状态信息都保存在备忘录中，并由管理者进行管理，这符合单一职责原则。</li>
</ul>
<p><strong>2，缺点：</strong></p>
<ul>
<li>资源消耗大。如果要保存的内部状态信息过多或者特别频繁，将会占用比较大的内存资源。</li>
</ul>
<h3 id="6105-使用场景"><a class="markdownIt-Anchor" href="#6105-使用场景">#</a> 6.10.5 使用场景</h3>
<ul>
<li>
<p>需要保存与恢复数据的场景，如玩游戏时的中间结果的存档功能。</p>
</li>
<li>
<p>需要提供一个可回滚操作的场景，如 Word、记事本、Photoshop，idea 等软件在编辑时按 Ctrl+Z 组合键，还有数据库中事务操作。</p>
</li>
</ul>
<h2 id="611-解释器模式"><a class="markdownIt-Anchor" href="#611-解释器模式">#</a> 6.11 解释器模式</h2>
<h3 id="6111-概述"><a class="markdownIt-Anchor" href="#6111-概述">#</a> 6.11.1 概述</h3>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420232619804.png"
                      alt="在这里插入图片描述"
                ></p>
<p>如上图，设计一个软件用来进行加减计算。我们第一想法就是使用工具类，提供对应的加法和减法的工具方法。</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//用于两个整数相加</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="type">int</span> <span class="title function_">add</span><span class="params">(<span class="type">int</span> a,<span class="type">int</span> b)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> a + b;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//用于两个整数相加</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="type">int</span> <span class="title function_">add</span><span class="params">(<span class="type">int</span> a,<span class="type">int</span> b,<span class="type">int</span> c)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> a + b + c;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//用于n个整数相加</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="type">int</span> <span class="title function_">add</span><span class="params">(Integer ... arr)</span> &#123;</span><br><span class="line">    <span class="type">int</span> <span class="variable">sum</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span> (Integer i : arr) &#123;</span><br><span class="line">        sum += i;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> sum;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>上面的形式比较单一、有限，如果形式变化非常多，这就不符合要求，因为加法和减法运算，两个运算符与数值可以有无限种组合方式。比如 1+2+3+4+5、1+2+3-4 等等。</p>
<p>显然，现在需要一种翻译识别机器，能够解析由数字以及 + - 符号构成的合法的运算序列。如果把运算符和数字都看作节点的话，能够逐个节点的进行读取解析运算，这就是解释器模式的思维。</p>
<p><strong>定义：</strong></p>
<blockquote>
<p>给定一个语言，定义它的文法表示，并定义一个解释器，这个解释器使用该标识来解释语言中的句子。</p>
</blockquote>
<p>在解释器模式中，我们需要将待解决的问题，提取出规则，抽象为一种 “语言”。比如加减法运算，规则为：由数值和 ± 符号组成的合法序列，“1+3-2” 就是这种语言的句子。</p>
<p>解释器就是要解析出来语句的含义。但是如何描述规则呢？</p>
<p><strong>文法（语法）规则：</strong></p>
<p>文法是用于描述语言的语法结构的形式规则。</p>
<div class="highlight-container" data-rel="Plaintext"><figure class="iseeu highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">expression ::= value | plus | minus</span><br><span class="line">plus ::= expression ‘+’ expression   </span><br><span class="line">minus ::= expression ‘-’ expression  </span><br><span class="line">value ::= integer</span><br></pre></td></tr></table></figure></div>
<blockquote>
<p>注意： 这里的符号 “::=” 表示 “定义为” 的意思，竖线 | 表示或，左右的其中一个，引号内为字符本身，引号外为语法。</p>
</blockquote>
<p>上面规则描述为 ：</p>
<p>表达式可以是一个值，也可以是 plus 或者 minus 运算，而 plus 和 minus 又是由表达式结合运算符构成，值的类型为整型数。</p>
<p><strong>抽象语法树：</strong></p>
<p>在计算机科学中，抽象语法树（AbstractSyntaxTree，AST），或简称语法树（Syntax tree），是源代码语法结构的一种抽象表示。它以树状的形式表现编程语言的语法结构，树上的每个节点都表示源代码中的一种结构。</p>
<p>用树形来表示符合文法规则的句子。</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420232642626.png"
                      alt="在这里插入图片描述"
                ></p>
<h3 id="6112-结构"><a class="markdownIt-Anchor" href="#6112-结构">#</a> 6.11.2 结构</h3>
<p>解释器模式包含以下主要角色。</p>
<ul>
<li>
<p>抽象表达式（Abstract Expression）角色：定义解释器的接口，约定解释器的解释操作，主要包含解释方法 interpret ()。</p>
</li>
<li>
<p>终结符表达式（Terminal  Expression）角色：是抽象表达式的子类，用来实现文法中与终结符相关的操作，文法中的每一个终结符都有一个具体终结表达式与之相对应。</p>
</li>
<li>
<p>非终结符表达式（Nonterminal Expression）角色：也是抽象表达式的子类，用来实现文法中与非终结符相关的操作，文法中的每条规则都对应于一个非终结符表达式。</p>
</li>
<li>
<p>环境（Context）角色：通常包含各个解释器需要的数据或是公共的功能，一般用来传递被所有解释器共享的数据，后面的解释器可以从这里获取这些值。</p>
</li>
<li>
<p>客户端（Client）：主要任务是将需要分析的句子或表达式转换成使用解释器对象描述的抽象语法树，然后调用解释器的解释方法，当然也可以通过环境角色间接访问解释器的解释方法。</p>
</li>
</ul>
<h3 id="6113-案例实现"><a class="markdownIt-Anchor" href="#6113-案例实现">#</a> 6.11.3 案例实现</h3>
<p>【例】设计实现加减法的软件</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420232705188.png"
                      alt="在这里插入图片描述"
                ></p>
<p>代码如下：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//抽象角色AbstractExpression</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title class_">AbstractExpression</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">abstract</span> <span class="type">int</span> <span class="title function_">interpret</span><span class="params">(Context context)</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//终结符表达式角色</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Value</span> <span class="keyword">extends</span> <span class="title class_">AbstractExpression</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> value;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Value</span><span class="params">(<span class="type">int</span> value)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.value = value;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">interpret</span><span class="params">(Context context)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> value;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">toString</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Integer</span>(value).toString();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//非终结符表达式角色  加法表达式</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Plus</span> <span class="keyword">extends</span> <span class="title class_">AbstractExpression</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> AbstractExpression left;</span><br><span class="line">    <span class="keyword">private</span> AbstractExpression right;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Plus</span><span class="params">(AbstractExpression left, AbstractExpression right)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.left = left;</span><br><span class="line">        <span class="built_in">this</span>.right = right;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">interpret</span><span class="params">(Context context)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> left.interpret(context) + right.interpret(context);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">toString</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;(&quot;</span> + left.toString() + <span class="string">&quot; + &quot;</span> + right.toString() + <span class="string">&quot;)&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">///非终结符表达式角色 减法表达式</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Minus</span> <span class="keyword">extends</span> <span class="title class_">AbstractExpression</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> AbstractExpression left;</span><br><span class="line">    <span class="keyword">private</span> AbstractExpression right;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Minus</span><span class="params">(AbstractExpression left, AbstractExpression right)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.left = left;</span><br><span class="line">        <span class="built_in">this</span>.right = right;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">interpret</span><span class="params">(Context context)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> left.interpret(context) - right.interpret(context);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">toString</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;(&quot;</span> + left.toString() + <span class="string">&quot; - &quot;</span> + right.toString() + <span class="string">&quot;)&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//终结符表达式角色 变量表达式</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Variable</span> <span class="keyword">extends</span> <span class="title class_">AbstractExpression</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Variable</span><span class="params">(String name)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">interpret</span><span class="params">(Context ctx)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> ctx.getValue(<span class="built_in">this</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">toString</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> name;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//环境类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Context</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> Map&lt;Variable, Integer&gt; map = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;Variable, Integer&gt;();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">assign</span><span class="params">(Variable <span class="keyword">var</span>, Integer value)</span> &#123;</span><br><span class="line">        map.put(<span class="keyword">var</span>, value);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">getValue</span><span class="params">(Variable <span class="keyword">var</span>)</span> &#123;</span><br><span class="line">        <span class="type">Integer</span> <span class="variable">value</span> <span class="operator">=</span> map.get(<span class="keyword">var</span>);</span><br><span class="line">        <span class="keyword">return</span> value;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//测试类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Client</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">Context</span> <span class="variable">context</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Context</span>();</span><br><span class="line"></span><br><span class="line">        <span class="type">Variable</span> <span class="variable">a</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Variable</span>(<span class="string">&quot;a&quot;</span>);</span><br><span class="line">        <span class="type">Variable</span> <span class="variable">b</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Variable</span>(<span class="string">&quot;b&quot;</span>);</span><br><span class="line">        <span class="type">Variable</span> <span class="variable">c</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Variable</span>(<span class="string">&quot;c&quot;</span>);</span><br><span class="line">        <span class="type">Variable</span> <span class="variable">d</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Variable</span>(<span class="string">&quot;d&quot;</span>);</span><br><span class="line">        <span class="type">Variable</span> <span class="variable">e</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Variable</span>(<span class="string">&quot;e&quot;</span>);</span><br><span class="line">        <span class="comment">//Value v = new Value(1);</span></span><br><span class="line"></span><br><span class="line">        context.assign(a, <span class="number">1</span>);</span><br><span class="line">        context.assign(b, <span class="number">2</span>);</span><br><span class="line">        context.assign(c, <span class="number">3</span>);</span><br><span class="line">        context.assign(d, <span class="number">4</span>);</span><br><span class="line">        context.assign(e, <span class="number">5</span>);</span><br><span class="line"></span><br><span class="line">        <span class="type">AbstractExpression</span> <span class="variable">expression</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Minus</span>(<span class="keyword">new</span> <span class="title class_">Plus</span>(<span class="keyword">new</span> <span class="title class_">Plus</span>(<span class="keyword">new</span> <span class="title class_">Plus</span>(a, b), c), d), e);</span><br><span class="line"></span><br><span class="line">        System.out.println(expression + <span class="string">&quot;= &quot;</span> + expression.interpret(context));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<h3 id="6114-优缺点"><a class="markdownIt-Anchor" href="#6114-优缺点">#</a> 6.11.4 优缺点</h3>
<p><strong>1，优点：</strong></p>
<ul>
<li>
<p>易于改变和扩展文法。</p>
<p>由于在解释器模式中使用类来表示语言的文法规则，因此可以通过继承等机制来改变或扩展文法。每一条文法规则都可以表示为一个类，因此可以方便地实现一个简单的语言。</p>
</li>
<li>
<p>实现文法较为容易。</p>
<p>在抽象语法树中每一个表达式节点类的实现方式都是相似的，这些类的代码编写都不会特别复杂。</p>
</li>
<li>
<p>增加新的解释表达式较为方便。</p>
<p>如果用户需要增加新的解释表达式只需要对应增加一个新的终结符表达式或非终结符表达式类，原有表达式类代码无须修改，符合 “开闭原则”。</p>
</li>
</ul>
<p><strong>2，缺点：</strong></p>
<ul>
<li>
<p>对于复杂文法难以维护。</p>
<p>在解释器模式中，每一条规则至少需要定义一个类，因此如果一个语言包含太多文法规则，类的个数将会急剧增加，导致系统难以管理和维护。</p>
</li>
</ul>
<ul>
<li>
<p>执行效率较低。</p>
<p>由于在解释器模式中使用了大量的循环和递归调用，因此在解释较为复杂的句子时其速度很慢，而且代码的调试过程也比较麻烦。</p>
</li>
</ul>
<h3 id="6115-使用场景"><a class="markdownIt-Anchor" href="#6115-使用场景">#</a> 6.11.5 使用场景</h3>
<ul>
<li>
<p>当语言的文法较为简单，且执行效率不是关键问题时。</p>
</li>
<li>
<p>当问题重复出现，且可以用一种简单的语言来进行表达时。</p>
</li>
<li>
<p>当一个语言需要解释执行，并且语言中的句子可以表示为一个抽象语法树的时候。</p>
</li>
</ul>
<h1 id="7自定义spring框架"><a class="markdownIt-Anchor" href="#7自定义spring框架">#</a> 7，自定义 Spring 框架</h1>
<h2 id="71-spring使用回顾"><a class="markdownIt-Anchor" href="#71-spring使用回顾">#</a> 7.1 spring 使用回顾</h2>
<p>自定义 spring 框架前，先回顾一下 spring 框架的使用，从而分析 spring 的核心，并对核心功能进行模拟。</p>
<ul>
<li>
<p>数据访问层。定义 UserDao 接口及其子实现类</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">UserDao</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">add</span><span class="params">()</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">UserDaoImpl</span> <span class="keyword">implements</span> <span class="title class_">UserDao</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">add</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;userDaoImpl ....&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
</li>
<li>
<p>业务逻辑层。定义 UserService 接口及其子实现类</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">UserService</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">add</span><span class="params">()</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">UserServiceImpl</span> <span class="keyword">implements</span> <span class="title class_">UserService</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> UserDao userDao;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setUserDao</span><span class="params">(UserDao userDao)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.userDao = userDao;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">add</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;userServiceImpl ...&quot;</span>);</span><br><span class="line">        userDao.add();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
</li>
<li>
<p>定义 UserController 类，使用 main 方法模拟 controller 层</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">UserController</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="comment">//创建spring容器对象</span></span><br><span class="line">        <span class="type">ApplicationContext</span> <span class="variable">applicationContext</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ClassPathXmlApplicationContext</span>(<span class="string">&quot;applicationContext.xml&quot;</span>);</span><br><span class="line">        <span class="comment">//从IOC容器中获取UserService对象</span></span><br><span class="line">        <span class="type">UserService</span> <span class="variable">userService</span> <span class="operator">=</span> applicationContext.getBean(<span class="string">&quot;userService&quot;</span>, UserService.class);</span><br><span class="line">        <span class="comment">//调用UserService对象的add方法</span></span><br><span class="line">        userService.add();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
</li>
<li>
<p>编写配置文件。在类路径下编写一个名为 ApplicationContext.xml 的配置文件</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span>?&gt;</span><br><span class="line">&lt;beans xmlns:xsi=<span class="string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span><br><span class="line">       xmlns=<span class="string">&quot;http://www.springframework.org/schema/beans&quot;</span></span><br><span class="line">       xmlns:context=<span class="string">&quot;http://www.springframework.org/schema/context&quot;</span></span><br><span class="line">       xsi:schemaLocation=<span class="string">&quot;http://www.springframework.org/schema/beans</span></span><br><span class="line"><span class="string">        http://www.springframework.org/schema/beans/spring-beans.xsd</span></span><br><span class="line"><span class="string">        http://www.springframework.org/schema/context</span></span><br><span class="line"><span class="string">        http://www.springframework.org/schema/context/spring-context.xsd&quot;</span>&gt;</span><br><span class="line"></span><br><span class="line">    &lt;bean id=<span class="string">&quot;userService&quot;</span> class=<span class="string">&quot;com.itheima.service.impl.UserServiceImpl&quot;</span>&gt;</span><br><span class="line">        &lt;property name=<span class="string">&quot;userDao&quot;</span> ref=<span class="string">&quot;userDao&quot;</span>&gt;&lt;/property&gt;</span><br><span class="line">    &lt;/bean&gt;</span><br><span class="line"></span><br><span class="line">    &lt;bean id=<span class="string">&quot;userDao&quot;</span> class=<span class="string">&quot;com.itheima.dao.impl.UserDaoImpl&quot;</span>&gt;&lt;/bean&gt;</span><br><span class="line"></span><br><span class="line">&lt;/beans&gt;</span><br></pre></td></tr></table></figure></div>
<p>代码运行结果如下：</p>
</li>
</ul>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/2021042023272395.png"
                      alt="在这里插入图片描述"
                ></p>
<p>通过上面代码及结果可以看出：</p>
<ul>
<li>userService 对象是从 applicationContext 容器对象获取到的，也就是 userService 对象交由 spring 进行管理。</li>
<li>上面结果可以看到调用了 UserDao 对象中的 add 方法，也就是说 UserDao 子实现类对象也交由 spring 管理了。</li>
<li>UserService 中的 userDao 变量我们并没有进行赋值，但是可以正常使用，说明 spring 已经将 UserDao 对象赋值给了 userDao 变量。</li>
</ul>
<p>上面三点体现了 Spring 框架的 IOC（Inversion of Control）和 DI（Dependency Injection, DI）</p>
<h2 id="72-spring核心功能结构"><a class="markdownIt-Anchor" href="#72-spring核心功能结构">#</a> 7.2 spring 核心功能结构</h2>
<p>Spring 大约有 20 个模块，由 1300 多个不同的文件构成。这些模块可以分为:</p>
<p>核心容器、AOP 和设备支持、数据访问与集成、Web 组件、通信报文和集成测试等，下面是 Spring 框架的总体架构图：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420232809922.png"
                      alt="在这里插入图片描述"
                ></p>
<p>核心容器由 beans、core、context 和 expression（Spring Expression Language，SpEL）4 个模块组成。</p>
<ul>
<li>spring-beans 和 spring-core 模块是 Spring 框架的核心模块，包含了控制反转（Inversion of Control，IOC）和依赖注入（Dependency Injection，DI）。BeanFactory 使用控制反转对应用程序的配置和依赖性规范与实际的应用程序代码进行了分离。BeanFactory 属于延时加载，也就是说在实例化容器对象后并不会自动实例化 Bean，只有当 Bean 被使用时，BeanFactory 才会对该 Bean 进行实例化与依赖关系的装配。</li>
<li>spring-context 模块构架于核心模块之上，扩展了 BeanFactory，为它添加了 Bean 生命周期控制、框架事件体系及资源加载透明化等功能。此外，该模块还提供了许多企业级支持，如邮件访问、远程访问、任务调度等，ApplicationContext 是该模块的核心接口，它的超类是 BeanFactory。与 BeanFactory 不同，ApplicationContext 实例化后会自动对所有的单实例 Bean 进行实例化与依赖关系的装配，使之处于待用状态。</li>
<li>spring-context-support 模块是对 Spring IoC 容器及 IoC 子容器的扩展支持。</li>
<li>spring-context-indexer 模块是 Spring 的类管理组件和 Classpath 扫描组件。</li>
<li>spring-expression 模块是统一表达式语言（EL）的扩展模块，可以查询、管理运行中的对象，同时也可以方便地调用对象方法，以及操作数组、集合等。它的语法类似于传统 EL，但提供了额外的功能，最出色的要数函数调用和简单字符串的模板函数。EL 的特性是基于 Spring 产品的需求而设计的，可以非常方便地同 Spring IoC 进行交互。</li>
</ul>
<h3 id="711-bean概述"><a class="markdownIt-Anchor" href="#711-bean概述">#</a> 7.1.1 bean 概述</h3>
<p>Spring 就是面向  <code>Bean</code>  的编程（BOP,Bean Oriented Programming），Bean 在 Spring 中处于核心地位。Bean 对于 Spring 的意义就像 Object 对于 OOP 的意义一样，Spring 中没有 Bean 也就没有 Spring 存在的意义。Spring IoC 容器通过配置文件或者注解的方式来管理 bean 对象之间的依赖关系。</p>
<p>spring 中 bean 用于对一个类进行封装。如下面的配置：</p>
<div class="highlight-container" data-rel="Xml"><figure class="iseeu highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">&quot;userService&quot;</span> <span class="attr">class</span>=<span class="string">&quot;com.itheima.service.impl.UserServiceImpl&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;userDao&quot;</span> <span class="attr">ref</span>=<span class="string">&quot;userDao&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">&quot;userDao&quot;</span> <span class="attr">class</span>=<span class="string">&quot;com.itheima.dao.impl.UserDaoImpl&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure></div>
<p>为什么 Bean 如此重要呢？</p>
<ul>
<li>spring 将 bean 对象交由一个叫 IOC 容器进行管理。</li>
<li>bean 对象之间的依赖关系在配置文件中体现，并由 spring 完成。</li>
</ul>
<h2 id="73-spring-ioc相关接口分析"><a class="markdownIt-Anchor" href="#73-spring-ioc相关接口分析">#</a> 7.3 Spring IOC 相关接口分析</h2>
<h3 id="731-beanfactory解析"><a class="markdownIt-Anchor" href="#731-beanfactory解析">#</a> 7.3.1 BeanFactory 解析</h3>
<p>Spring 中 Bean 的创建是典型的工厂模式，这一系列的 Bean 工厂，即 IoC 容器，为开发者管理对象之间的依赖关系提供了很多便利和基础服务，在 Spring 中有许多 IoC 容器的实现供用户选择，其相互关系如下图所示。</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420232829541.png"
                      alt="在这里插入图片描述"
                ></p>
<p>其中，BeanFactory 作为最顶层的一个接口，定义了 IoC 容器的基本功能规范，BeanFactory 有三个重要的子接口：ListableBeanFactory、HierarchicalBeanFactory 和 AutowireCapableBeanFactory。但是从类图中我们可以发现最终的默认实现类是 DefaultListableBeanFactory，它实现了所有的接口。</p>
<p>那么为何要定义这么多层次的接口呢？</p>
<p>每个接口都有它的使用场合，主要是为了区分在 Spring 内部操作过程中对象的传递和转化，对对象的数据访问所做的限制。例如，</p>
<ul>
<li>ListableBeanFactory 接口表示这些 Bean 可列表化。</li>
<li>HierarchicalBeanFactory 表示这些 Bean 是有继承关系的，也就是每个 Bean 可能有父 Bean</li>
<li>AutowireCapableBeanFactory 接口定义 Bean 的自动装配规则。</li>
</ul>
<p>这三个接口共同定义了 Bean 的集合、Bean 之间的关系及 Bean 行为。最基本的 IoC 容器接口是 BeanFactory，来看一下它的源码：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">BeanFactory</span> &#123;</span><br><span class="line"></span><br><span class="line">	<span class="type">String</span> <span class="variable">FACTORY_BEAN_PREFIX</span> <span class="operator">=</span> <span class="string">&quot;&amp;&quot;</span>;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//根据bean的名称获取IOC容器中的的bean对象</span></span><br><span class="line">	Object <span class="title function_">getBean</span><span class="params">(String name)</span> <span class="keyword">throws</span> BeansException;</span><br><span class="line">	<span class="comment">//根据bean的名称获取IOC容器中的的bean对象，并指定获取到的bean对象的类型，这样我们使用时就不需要进行类型强转了</span></span><br><span class="line">	&lt;T&gt; T <span class="title function_">getBean</span><span class="params">(String name, Class&lt;T&gt; requiredType)</span> <span class="keyword">throws</span> BeansException;</span><br><span class="line">	Object <span class="title function_">getBean</span><span class="params">(String name, Object... args)</span> <span class="keyword">throws</span> BeansException;</span><br><span class="line">	&lt;T&gt; T <span class="title function_">getBean</span><span class="params">(Class&lt;T&gt; requiredType)</span> <span class="keyword">throws</span> BeansException;</span><br><span class="line">	&lt;T&gt; T <span class="title function_">getBean</span><span class="params">(Class&lt;T&gt; requiredType, Object... args)</span> <span class="keyword">throws</span> BeansException;</span><br><span class="line">	</span><br><span class="line">	&lt;T&gt; ObjectProvider&lt;T&gt; <span class="title function_">getBeanProvider</span><span class="params">(Class&lt;T&gt; requiredType)</span>;</span><br><span class="line">	&lt;T&gt; ObjectProvider&lt;T&gt; <span class="title function_">getBeanProvider</span><span class="params">(ResolvableType requiredType)</span>;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//判断容器中是否包含指定名称的bean对象</span></span><br><span class="line">	<span class="type">boolean</span> <span class="title function_">containsBean</span><span class="params">(String name)</span>;</span><br><span class="line">	<span class="comment">//根据bean的名称判断是否是单例</span></span><br><span class="line">	<span class="type">boolean</span> <span class="title function_">isSingleton</span><span class="params">(String name)</span> <span class="keyword">throws</span> NoSuchBeanDefinitionException;</span><br><span class="line">	<span class="type">boolean</span> <span class="title function_">isPrototype</span><span class="params">(String name)</span> <span class="keyword">throws</span> NoSuchBeanDefinitionException;</span><br><span class="line">	<span class="type">boolean</span> <span class="title function_">isTypeMatch</span><span class="params">(String name, ResolvableType typeToMatch)</span> <span class="keyword">throws</span> NoSuchBeanDefinitionException;</span><br><span class="line">	<span class="type">boolean</span> <span class="title function_">isTypeMatch</span><span class="params">(String name, Class&lt;?&gt; typeToMatch)</span> <span class="keyword">throws</span> NoSuchBeanDefinitionException;</span><br><span class="line">	<span class="meta">@Nullable</span></span><br><span class="line">	Class&lt;?&gt; getType(String name) <span class="keyword">throws</span> NoSuchBeanDefinitionException;</span><br><span class="line">	String[] getAliases(String name);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>在 BeanFactory 里只对 IoC 容器的基本行为做了定义，根本不关心你的 Bean 是如何定义及怎样加载的。正如我们只关心能从工厂里得到什么产品，不关心工厂是怎么生产这些产品的。</p>
<p>BeanFactory 有一个很重要的子接口，就是 ApplicationContext 接口，该接口主要来规范容器中的 bean 对象是非延时加载，即在创建容器对象的时候就对象 bean 进行初始化，并存储到一个容器中。</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420232844936.png"
                      alt="在这里插入图片描述"
                ></p>
<p>要知道工厂是如何产生对象的，我们需要看具体的 IoC 容器实现，Spring 提供了许多 IoC 容器实现，比如：</p>
<ul>
<li>ClasspathXmlApplicationContext : 根据类路径加载 xml 配置文件，并创建 IOC 容器对象。</li>
<li>FileSystemXmlApplicationContext ：根据系统路径加载 xml 配置文件，并创建 IOC 容器对象。</li>
<li>AnnotationConfigApplicationContext ：加载注解类配置，并创建 IOC 容器。</li>
</ul>
<h3 id="732-beandefinition解析"><a class="markdownIt-Anchor" href="#732-beandefinition解析">#</a> 7.3.2 BeanDefinition 解析</h3>
<p>Spring IoC 容器管理我们定义的各种 Bean 对象及其相互关系，而 Bean 对象在 Spring 实现中是以 BeanDefinition 来描述的，如下面配置文件</p>
<div class="highlight-container" data-rel="Xml"><figure class="iseeu highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">&quot;userDao&quot;</span> <span class="attr">class</span>=<span class="string">&quot;com.itheima.dao.impl.UserDaoImpl&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">bean标签还有很多属性：</span><br><span class="line">	scope、init-method、destory-method等。</span><br></pre></td></tr></table></figure></div>
<p>其继承体系如下图所示。</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420232911848.png"
                      alt="在这里插入图片描述"
                ></p>
<h3 id="733-beandefinitionreader解析"><a class="markdownIt-Anchor" href="#733-beandefinitionreader解析">#</a> 7.3.3 BeanDefinitionReader 解析</h3>
<p>Bean 的解析过程非常复杂，功能被分得很细，因为这里需要被扩展的地方很多，必须保证足够的灵活性，以应对可能的变化。Bean 的解析主要就是对 Spring 配置文件的解析。这个解析过程主要通过 BeanDefinitionReader 来完成，看看 Spring 中 BeanDefinitionReader 的类结构图，如下图所示。</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420232930473.png"
                      alt="在这里插入图片描述"
                ></p>
<p>看看 BeanDefinitionReader 接口定义的功能来理解它具体的作用：</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">BeanDefinitionReader</span> &#123;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//获取BeanDefinitionRegistry注册器对象</span></span><br><span class="line">	BeanDefinitionRegistry <span class="title function_">getRegistry</span><span class="params">()</span>;</span><br><span class="line"></span><br><span class="line">	<span class="meta">@Nullable</span></span><br><span class="line">	ResourceLoader <span class="title function_">getResourceLoader</span><span class="params">()</span>;</span><br><span class="line"></span><br><span class="line">	<span class="meta">@Nullable</span></span><br><span class="line">	ClassLoader <span class="title function_">getBeanClassLoader</span><span class="params">()</span>;</span><br><span class="line"></span><br><span class="line">	BeanNameGenerator <span class="title function_">getBeanNameGenerator</span><span class="params">()</span>;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/*</span></span><br><span class="line"><span class="comment">		下面的loadBeanDefinitions都是加载bean定义，从指定的资源中</span></span><br><span class="line"><span class="comment">	*/</span></span><br><span class="line">	<span class="type">int</span> <span class="title function_">loadBeanDefinitions</span><span class="params">(Resource resource)</span> <span class="keyword">throws</span> BeanDefinitionStoreException;</span><br><span class="line">	<span class="type">int</span> <span class="title function_">loadBeanDefinitions</span><span class="params">(Resource... resources)</span> <span class="keyword">throws</span> BeanDefinitionStoreException;</span><br><span class="line">	<span class="type">int</span> <span class="title function_">loadBeanDefinitions</span><span class="params">(String location)</span> <span class="keyword">throws</span> BeanDefinitionStoreException;</span><br><span class="line">	<span class="type">int</span> <span class="title function_">loadBeanDefinitions</span><span class="params">(String... locations)</span> <span class="keyword">throws</span> BeanDefinitionStoreException;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<h3 id="734-beandefinitionregistry解析"><a class="markdownIt-Anchor" href="#734-beandefinitionregistry解析">#</a> 7.3.4 BeanDefinitionRegistry 解析</h3>
<p>BeanDefinitionReader 用来解析 bean 定义，并封装 BeanDefinition 对象，而我们定义的配置文件中定义了很多 bean 标签，所以就有一个问题，解析的 BeanDefinition 对象存储到哪儿？答案就是 BeanDefinition 的注册中心，而该注册中心顶层接口就是 BeanDefinitionRegistry。</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">BeanDefinitionRegistry</span> <span class="keyword">extends</span> <span class="title class_">AliasRegistry</span> &#123;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//往注册表中注册bean</span></span><br><span class="line">	<span class="keyword">void</span> <span class="title function_">registerBeanDefinition</span><span class="params">(String beanName, BeanDefinition beanDefinition)</span></span><br><span class="line">			<span class="keyword">throws</span> BeanDefinitionStoreException;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//从注册表中删除指定名称的bean</span></span><br><span class="line">	<span class="keyword">void</span> <span class="title function_">removeBeanDefinition</span><span class="params">(String beanName)</span> <span class="keyword">throws</span> NoSuchBeanDefinitionException;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//获取注册表中指定名称的bean</span></span><br><span class="line">	BeanDefinition <span class="title function_">getBeanDefinition</span><span class="params">(String beanName)</span> <span class="keyword">throws</span> NoSuchBeanDefinitionException;</span><br><span class="line">    </span><br><span class="line">	<span class="comment">//判断注册表中是否已经注册了指定名称的bean</span></span><br><span class="line">	<span class="type">boolean</span> <span class="title function_">containsBeanDefinition</span><span class="params">(String beanName)</span>;</span><br><span class="line">    </span><br><span class="line">	<span class="comment">//获取注册表中所有的bean的名称</span></span><br><span class="line">	String[] getBeanDefinitionNames();</span><br><span class="line">    </span><br><span class="line">	<span class="type">int</span> <span class="title function_">getBeanDefinitionCount</span><span class="params">()</span>;</span><br><span class="line">	<span class="type">boolean</span> <span class="title function_">isBeanNameInUse</span><span class="params">(String beanName)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>继承结构图如下：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="http://tuchuang.wenhe9.cn/20210420232952954.png"
                      alt="在这里插入图片描述"
                ></p>
<p>从上面类图可以看到 BeanDefinitionRegistry 接口的子实现类主要有以下几个：</p>
<ul>
<li>
<p>DefaultListableBeanFactory</p>
<p>在该类中定义了如下代码，就是用来注册 bean</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> Map&lt;String, BeanDefinition&gt; beanDefinitionMap = <span class="keyword">new</span> <span class="title class_">ConcurrentHashMap</span>&lt;&gt;(<span class="number">256</span>);</span><br></pre></td></tr></table></figure></div>
</li>
<li>
<p>SimpleBeanDefinitionRegistry</p>
<p>在该类中定义了如下代码，就是用来注册 bean</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> Map&lt;String, BeanDefinition&gt; beanDefinitionMap = <span class="keyword">new</span> <span class="title class_">ConcurrentHashMap</span>&lt;&gt;(<span class="number">64</span>);</span><br></pre></td></tr></table></figure></div>
</li>
</ul>
<h3 id="735-创建容器"><a class="markdownIt-Anchor" href="#735-创建容器">#</a> 7.3.5 创建容器</h3>
<p>ClassPathXmlApplicationContext 对 Bean 配置资源的载入是从 refresh（）方法开始的。refresh（）方法是一个模板方法，规定了 IoC 容器的启动流程，有些逻辑要交给其子类实现。它对 Bean 配置资源进行载入，ClassPathXmlApplicationContext 通过调用其父类 AbstractApplicationContext 的 refresh（）方法启动整个 IoC 容器对 Bean 定义的载入过程。</p>
<h2 id="74-自定义springioc"><a class="markdownIt-Anchor" href="#74-自定义springioc">#</a> 7.4 自定义 SpringIOC</h2>
<p>现要对下面的配置文件进行解析，并自定义 Spring 框架的 IOC 对涉及到的对象进行管理。</p>
<div class="highlight-container" data-rel="Xml"><figure class="iseeu highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span>?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">&quot;userService&quot;</span> <span class="attr">class</span>=<span class="string">&quot;com.itheima.service.impl.UserServiceImpl&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;userDao&quot;</span> <span class="attr">ref</span>=<span class="string">&quot;userDao&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">&quot;userDao&quot;</span> <span class="attr">class</span>=<span class="string">&quot;com.itheima.dao.impl.UserDaoImpl&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure></div>
<h3 id="741-定义bean相关的pojo类"><a class="markdownIt-Anchor" href="#741-定义bean相关的pojo类">#</a> 7.4.1 定义 bean 相关的 pojo 类</h3>
<h4 id="7411-propertyvalue类"><a class="markdownIt-Anchor" href="#7411-propertyvalue类">#</a> 7.4.1.1 PropertyValue 类</h4>
<p>用于封装 bean 的属性，体现到上面的配置文件就是封装 bean 标签的子标签 property 标签数据。</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">PropertyValue</span> &#123;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">private</span> String name;</span><br><span class="line">  <span class="keyword">private</span> String ref;</span><br><span class="line">  <span class="keyword">private</span> String value;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">public</span> <span class="title function_">PropertyValue</span><span class="params">()</span> &#123;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">public</span> <span class="title function_">PropertyValue</span><span class="params">(String name, String ref,String value)</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.name = name;</span><br><span class="line">    <span class="built_in">this</span>.ref = ref;</span><br><span class="line">    <span class="built_in">this</span>.value = value;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">public</span> String <span class="title function_">getName</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> name;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setName</span><span class="params">(String name)</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.name = name;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">public</span> String <span class="title function_">getRef</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> ref;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setRef</span><span class="params">(String ref)</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.ref = ref;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">public</span> String <span class="title function_">getValue</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> value;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setValue</span><span class="params">(String value)</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.value = value;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<h4 id="7412-mutablepropertyvalues类"><a class="markdownIt-Anchor" href="#7412-mutablepropertyvalues类">#</a> 7.4.1.2 MutablePropertyValues 类</h4>
<p>一个 bean 标签可以有多个 property 子标签，所以再定义一个 MutablePropertyValues 类，用来存储并管理多个 PropertyValue 对象。</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MutablePropertyValues</span> <span class="keyword">implements</span> <span class="title class_">Iterable</span>&lt;PropertyValue&gt; &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> List&lt;PropertyValue&gt; propertyValueList;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">MutablePropertyValues</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.propertyValueList = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;PropertyValue&gt;();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">MutablePropertyValues</span><span class="params">(List&lt;PropertyValue&gt; propertyValueList)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.propertyValueList = (propertyValueList != <span class="literal">null</span> ? propertyValueList : <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;PropertyValue&gt;());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> PropertyValue[] getPropertyValues() &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span>.propertyValueList.toArray(<span class="keyword">new</span> <span class="title class_">PropertyValue</span>[<span class="number">0</span>]);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> PropertyValue <span class="title function_">getPropertyValue</span><span class="params">(String propertyName)</span> &#123;</span><br><span class="line">        <span class="keyword">for</span> (PropertyValue pv : <span class="built_in">this</span>.propertyValueList) &#123;</span><br><span class="line">            <span class="keyword">if</span> (pv.getName().equals(propertyName)) &#123;</span><br><span class="line">                <span class="keyword">return</span> pv;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> Iterator&lt;PropertyValue&gt; <span class="title function_">iterator</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> propertyValueList.iterator();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="type">boolean</span> <span class="title function_">isEmpty</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span>.propertyValueList.isEmpty();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> MutablePropertyValues <span class="title function_">addPropertyValue</span><span class="params">(PropertyValue pv)</span> &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="built_in">this</span>.propertyValueList.size(); i++) &#123;</span><br><span class="line">            <span class="type">PropertyValue</span> <span class="variable">currentPv</span> <span class="operator">=</span> <span class="built_in">this</span>.propertyValueList.get(i);</span><br><span class="line">            <span class="keyword">if</span> (currentPv.getName().equals(pv.getName())) &#123;</span><br><span class="line">                <span class="built_in">this</span>.propertyValueList.set(i, <span class="keyword">new</span> <span class="title class_">PropertyValue</span>(pv.getName(),pv.getRef(), pv.getValue()));</span><br><span class="line">                <span class="keyword">return</span> <span class="built_in">this</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">this</span>.propertyValueList.add(pv);</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="type">boolean</span> <span class="title function_">contains</span><span class="params">(String propertyName)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> getPropertyValue(propertyName) != <span class="literal">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<h4 id="7413-beandefinition类"><a class="markdownIt-Anchor" href="#7413-beandefinition类">#</a> 7.4.1.3 BeanDefinition 类</h4>
<p>BeanDefinition 类用来封装 bean 信息的，主要包含 id（即 bean 对象的名称）、class（需要交由 spring 管理的类的全类名）及子标签 property 数据。</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">BeanDefinition</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> String id;</span><br><span class="line">    <span class="keyword">private</span> String className;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> MutablePropertyValues propertyValues;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">BeanDefinition</span><span class="params">()</span> &#123;</span><br><span class="line">        propertyValues = <span class="keyword">new</span> <span class="title class_">MutablePropertyValues</span>();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getId</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> id;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setId</span><span class="params">(String id)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.id = id;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getClassName</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> className;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setClassName</span><span class="params">(String className)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.className = className;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setPropertyValues</span><span class="params">(MutablePropertyValues propertyValues)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.propertyValues = propertyValues;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> MutablePropertyValues <span class="title function_">getPropertyValues</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> propertyValues;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<h3 id="742-定义注册表相关类"><a class="markdownIt-Anchor" href="#742-定义注册表相关类">#</a> 7.4.2 定义注册表相关类</h3>
<h4 id="7421-beandefinitionregistry接口"><a class="markdownIt-Anchor" href="#7421-beandefinitionregistry接口">#</a> 7.4.2.1 BeanDefinitionRegistry 接口</h4>
<p>BeanDefinitionRegistry 接口定义了注册表的相关操作，定义如下功能：</p>
<ul>
<li>注册 BeanDefinition 对象到注册表中</li>
<li>从注册表中删除指定名称的 BeanDefinition 对象</li>
<li>根据名称从注册表中获取 BeanDefinition 对象</li>
<li>判断注册表中是否包含指定名称的 BeanDefinition 对象</li>
<li>获取注册表中 BeanDefinition 对象的个数</li>
<li>获取注册表中所有的 BeanDefinition 的名称</li>
</ul>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">BeanDefinitionRegistry</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//注册BeanDefinition对象到注册表中</span></span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">registerBeanDefinition</span><span class="params">(String beanName, BeanDefinition beanDefinition)</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//从注册表中删除指定名称的BeanDefinition对象</span></span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">removeBeanDefinition</span><span class="params">(String beanName)</span> <span class="keyword">throws</span> Exception;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//根据名称从注册表中获取BeanDefinition对象</span></span><br><span class="line">    BeanDefinition <span class="title function_">getBeanDefinition</span><span class="params">(String beanName)</span> <span class="keyword">throws</span> Exception;</span><br><span class="line"></span><br><span class="line">    <span class="type">boolean</span> <span class="title function_">containsBeanDefinition</span><span class="params">(String beanName)</span>;</span><br><span class="line"></span><br><span class="line">    <span class="type">int</span> <span class="title function_">getBeanDefinitionCount</span><span class="params">()</span>;</span><br><span class="line"></span><br><span class="line">    String[] getBeanDefinitionNames();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<h4 id="7422-simplebeandefinitionregistry类"><a class="markdownIt-Anchor" href="#7422-simplebeandefinitionregistry类">#</a> 7.4.2.2 SimpleBeanDefinitionRegistry 类</h4>
<p>该类实现了 BeanDefinitionRegistry 接口，定义了 Map 集合作为注册表容器。</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">SimpleBeanDefinitionRegistry</span> <span class="keyword">implements</span> <span class="title class_">BeanDefinitionRegistry</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Map&lt;String, BeanDefinition&gt; beanDefinitionMap = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;String, BeanDefinition&gt;();</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">registerBeanDefinition</span><span class="params">(String beanName, BeanDefinition beanDefinition)</span> &#123;</span><br><span class="line">        beanDefinitionMap.put(beanName,beanDefinition);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">removeBeanDefinition</span><span class="params">(String beanName)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        beanDefinitionMap.remove(beanName);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> BeanDefinition <span class="title function_">getBeanDefinition</span><span class="params">(String beanName)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="keyword">return</span> beanDefinitionMap.get(beanName);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="type">boolean</span> <span class="title function_">containsBeanDefinition</span><span class="params">(String beanName)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> beanDefinitionMap.containsKey(beanName);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">getBeanDefinitionCount</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> beanDefinitionMap.size();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> String[] getBeanDefinitionNames() &#123;</span><br><span class="line">        <span class="keyword">return</span> beanDefinitionMap.keySet().toArray(<span class="keyword">new</span> <span class="title class_">String</span>[<span class="number">1</span>]);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<h3 id="743-定义解析器相关类"><a class="markdownIt-Anchor" href="#743-定义解析器相关类">#</a> 7.4.3 定义解析器相关类</h3>
<h4 id="7431-beandefinitionreader接口"><a class="markdownIt-Anchor" href="#7431-beandefinitionreader接口">#</a> 7.4.3.1 BeanDefinitionReader 接口</h4>
<p>BeanDefinitionReader 是用来解析配置文件并在注册表中注册 bean 的信息。定义了两个规范：</p>
<ul>
<li>获取注册表的功能，让外界可以通过该对象获取注册表对象。</li>
<li>加载配置文件，并注册 bean 数据。</li>
</ul>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">BeanDefinitionReader</span> &#123;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//获取注册表对象</span></span><br><span class="line">    BeanDefinitionRegistry <span class="title function_">getRegistry</span><span class="params">()</span>;</span><br><span class="line">	<span class="comment">//加载配置文件并在注册表中进行注册</span></span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">loadBeanDefinitions</span><span class="params">(String configLocation)</span> <span class="keyword">throws</span> Exception;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<h4 id="7432-xmlbeandefinitionreader类"><a class="markdownIt-Anchor" href="#7432-xmlbeandefinitionreader类">#</a> 7.4.3.2 XmlBeanDefinitionReader 类</h4>
<p>XmlBeanDefinitionReader 类是专门用来解析 xml 配置文件的。该类实现 BeanDefinitionReader 接口并实现接口中的两个功能。</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">XmlBeanDefinitionReader</span> <span class="keyword">implements</span> <span class="title class_">BeanDefinitionReader</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> BeanDefinitionRegistry registry;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">XmlBeanDefinitionReader</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.registry = <span class="keyword">new</span> <span class="title class_">SimpleBeanDefinitionRegistry</span>();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> BeanDefinitionRegistry <span class="title function_">getRegistry</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> registry;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">loadBeanDefinitions</span><span class="params">(String configLocation)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line"></span><br><span class="line">        <span class="type">InputStream</span> <span class="variable">is</span> <span class="operator">=</span> <span class="built_in">this</span>.getClass().getClassLoader().getResourceAsStream(configLocation);</span><br><span class="line">        <span class="type">SAXReader</span> <span class="variable">reader</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">SAXReader</span>();</span><br><span class="line">        <span class="type">Document</span> <span class="variable">document</span> <span class="operator">=</span> reader.read(is);</span><br><span class="line">        <span class="type">Element</span> <span class="variable">rootElement</span> <span class="operator">=</span> document.getRootElement();</span><br><span class="line">        <span class="comment">//解析bean标签</span></span><br><span class="line">        parseBean(rootElement);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">void</span> <span class="title function_">parseBean</span><span class="params">(Element rootElement)</span> &#123;</span><br><span class="line"></span><br><span class="line">        List&lt;Element&gt; elements = rootElement.elements();</span><br><span class="line">        <span class="keyword">for</span> (Element element : elements) &#123;</span><br><span class="line">            <span class="type">String</span> <span class="variable">id</span> <span class="operator">=</span> element.attributeValue(<span class="string">&quot;id&quot;</span>);</span><br><span class="line">            <span class="type">String</span> <span class="variable">className</span> <span class="operator">=</span> element.attributeValue(<span class="string">&quot;class&quot;</span>);</span><br><span class="line">            <span class="type">BeanDefinition</span> <span class="variable">beanDefinition</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">BeanDefinition</span>();</span><br><span class="line">            beanDefinition.setId(id);</span><br><span class="line">            beanDefinition.setClassName(className);</span><br><span class="line">            List&lt;Element&gt; list = element.elements(<span class="string">&quot;property&quot;</span>);</span><br><span class="line">            <span class="type">MutablePropertyValues</span> <span class="variable">mutablePropertyValues</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">MutablePropertyValues</span>();</span><br><span class="line">            <span class="keyword">for</span> (Element element1 : list) &#123;</span><br><span class="line">                <span class="type">String</span> <span class="variable">name</span> <span class="operator">=</span> element1.attributeValue(<span class="string">&quot;name&quot;</span>);</span><br><span class="line">                <span class="type">String</span> <span class="variable">ref</span> <span class="operator">=</span> element1.attributeValue(<span class="string">&quot;ref&quot;</span>);</span><br><span class="line">                <span class="type">String</span> <span class="variable">value</span> <span class="operator">=</span> element1.attributeValue(<span class="string">&quot;value&quot;</span>);</span><br><span class="line">                <span class="type">PropertyValue</span> <span class="variable">propertyValue</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">PropertyValue</span>(name,ref,value);</span><br><span class="line">                mutablePropertyValues.addPropertyValue(propertyValue);</span><br><span class="line">            &#125;</span><br><span class="line">            beanDefinition.setPropertyValues(mutablePropertyValues);</span><br><span class="line"></span><br><span class="line">            registry.registerBeanDefinition(id,beanDefinition);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<h3 id="744-ioc容器相关类"><a class="markdownIt-Anchor" href="#744-ioc容器相关类">#</a> 7.4.4 IOC 容器相关类</h3>
<h4 id="7441-beanfactory接口"><a class="markdownIt-Anchor" href="#7441-beanfactory接口">#</a> 7.4.4.1 BeanFactory 接口</h4>
<p>在该接口中定义 IOC 容器的统一规范即获取 bean 对象。</p>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">BeanFactory</span> &#123;</span><br><span class="line">	<span class="comment">//根据bean对象的名称获取bean对象</span></span><br><span class="line">    Object <span class="title function_">getBean</span><span class="params">(String name)</span> <span class="keyword">throws</span> Exception;</span><br><span class="line">	<span class="comment">//根据bean对象的名称获取bean对象，并进行类型转换</span></span><br><span class="line">    &lt;T&gt; T <span class="title function_">getBean</span><span class="params">(String name, Class&lt;? extends T&gt; clazz)</span> <span class="keyword">throws</span> Exception;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<h4 id="7442-applicationcontext接口"><a class="markdownIt-Anchor" href="#7442-applicationcontext接口">#</a> 7.4.4.2 ApplicationContext 接口</h4>
<p>该接口的所以的子实现类对 bean 对象的创建都是非延时的，所以在该接口中定义  <code>refresh()</code>  方法，该方法主要完成以下两个功能：</p>
<ul>
<li>加载配置文件。</li>
<li>根据注册表中的 BeanDefinition 对象封装的数据进行 bean 对象的创建。</li>
</ul>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">ApplicationContext</span> <span class="keyword">extends</span> <span class="title class_">BeanFactory</span> &#123;</span><br><span class="line">	<span class="comment">//进行配置文件加载并进行对象创建</span></span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">refresh</span><span class="params">()</span> <span class="keyword">throws</span> IllegalStateException, Exception;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<h4 id="7443-abstractapplicationcontext类"><a class="markdownIt-Anchor" href="#7443-abstractapplicationcontext类">#</a> 7.4.4.3 AbstractApplicationContext 类</h4>
<ul>
<li>
<p>作为 ApplicationContext 接口的子类，所以该类也是非延时加载，所以需要在该类中定义一个 Map 集合，作为 bean 对象存储的容器。</p>
</li>
<li>
<p>声明 BeanDefinitionReader 类型的变量，用来进行 xml 配置文件的解析，符合单一职责原则。</p>
<p>BeanDefinitionReader 类型的对象创建交由子类实现，因为只有子类明确到底创建 BeanDefinitionReader 哪儿个子实现类对象。</p>
</li>
</ul>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title class_">AbstractApplicationContext</span> <span class="keyword">implements</span> <span class="title class_">ApplicationContext</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">protected</span> BeanDefinitionReader beanDefinitionReader;</span><br><span class="line">    <span class="comment">//用来存储bean对象的容器   key存储的是bean的id值，value存储的是bean对象</span></span><br><span class="line">    <span class="keyword">protected</span> Map&lt;String, Object&gt; singletonObjects = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;String, Object&gt;();</span><br><span class="line"></span><br><span class="line">    <span class="comment">//存储配置文件的路径</span></span><br><span class="line">    <span class="keyword">protected</span> String configLocation;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">refresh</span><span class="params">()</span> <span class="keyword">throws</span> IllegalStateException, Exception &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//加载BeanDefinition</span></span><br><span class="line">        beanDefinitionReader.loadBeanDefinitions(configLocation);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//初始化bean</span></span><br><span class="line">        finishBeanInitialization();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//bean的初始化</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">void</span> <span class="title function_">finishBeanInitialization</span><span class="params">()</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="type">BeanDefinitionRegistry</span> <span class="variable">registry</span> <span class="operator">=</span> beanDefinitionReader.getRegistry();</span><br><span class="line">        String[] beanNames = registry.getBeanDefinitionNames();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (String beanName : beanNames) &#123;</span><br><span class="line">            <span class="type">BeanDefinition</span> <span class="variable">beanDefinition</span> <span class="operator">=</span> registry.getBeanDefinition(beanName);</span><br><span class="line">            getBean(beanName);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<blockquote>
<p>注意：该类 finishBeanInitialization () 方法中调用 getBean () 方法使用到了模板方法模式。</p>
</blockquote>
<h4 id="7444-classpathxmlapplicationcontext类"><a class="markdownIt-Anchor" href="#7444-classpathxmlapplicationcontext类">#</a> 7.4.4.4 ClassPathXmlApplicationContext 类</h4>
<p>该类主要是加载类路径下的配置文件，并进行 bean 对象的创建，主要完成以下功能：</p>
<ul>
<li>在构造方法中，创建 BeanDefinitionReader 对象。</li>
<li>在构造方法中，调用 refresh () 方法，用于进行配置文件加载、创建 bean 对象并存储到容器中。</li>
<li>重写父接口中的 getBean () 方法，并实现依赖注入操作。</li>
</ul>
<div class="highlight-container" data-rel="Java"><figure class="iseeu highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ClassPathXmlApplicationContext</span> <span class="keyword">extends</span> <span class="title class_">AbstractApplicationContext</span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">ClassPathXmlApplicationContext</span><span class="params">(String configLocation)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.configLocation = configLocation;</span><br><span class="line">        <span class="comment">//构建XmlBeanDefinitionReader对象</span></span><br><span class="line">        beanDefinitionReader = <span class="keyword">new</span> <span class="title class_">XmlBeanDefinitionReader</span>();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="built_in">this</span>.refresh();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//根据bean的id属性值获取bean对象</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> Object <span class="title function_">getBean</span><span class="params">(String name)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//return singletonObjects.get(name);</span></span><br><span class="line">        <span class="type">Object</span> <span class="variable">obj</span> <span class="operator">=</span> singletonObjects.get(name);</span><br><span class="line">        <span class="keyword">if</span>(obj != <span class="literal">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> obj;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="type">BeanDefinitionRegistry</span> <span class="variable">registry</span> <span class="operator">=</span> beanDefinitionReader.getRegistry();</span><br><span class="line">        <span class="type">BeanDefinition</span> <span class="variable">beanDefinition</span> <span class="operator">=</span> registry.getBeanDefinition(name);</span><br><span class="line">        <span class="keyword">if</span>(beanDefinition == <span class="literal">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="type">String</span> <span class="variable">className</span> <span class="operator">=</span> beanDefinition.getClassName();</span><br><span class="line">        Class&lt;?&gt; clazz = Class.forName(className);</span><br><span class="line">        <span class="type">Object</span> <span class="variable">beanObj</span> <span class="operator">=</span> clazz.newInstance();</span><br><span class="line">        <span class="type">MutablePropertyValues</span> <span class="variable">propertyValues</span> <span class="operator">=</span> beanDefinition.getPropertyValues();</span><br><span class="line">        <span class="keyword">for</span> (PropertyValue propertyValue : propertyValues) &#123;</span><br><span class="line">            <span class="type">String</span> <span class="variable">propertyName</span> <span class="operator">=</span> propertyValue.getName();</span><br><span class="line">            <span class="type">String</span> <span class="variable">value</span> <span class="operator">=</span> propertyValue.getValue();</span><br><span class="line">            <span class="type">String</span> <span class="variable">ref</span> <span class="operator">=</span> propertyValue.getRef();</span><br><span class="line">            <span class="keyword">if</span>(ref != <span class="literal">null</span> &amp;&amp; !<span class="string">&quot;&quot;</span>.equals(ref)) &#123;</span><br><span class="line"></span><br><span class="line">                <span class="type">Object</span> <span class="variable">bean</span> <span class="operator">=</span> getBean(ref);</span><br><span class="line">                <span class="type">String</span> <span class="variable">methodName</span> <span class="operator">=</span> StringUtils.getSetterMethodNameByFieldName(propertyName);</span><br><span class="line">                Method[] methods = clazz.getMethods();</span><br><span class="line">                <span class="keyword">for</span> (Method method : methods) &#123;</span><br><span class="line">                    <span class="keyword">if</span>(method.getName().equals(methodName)) &#123;</span><br><span class="line">                        method.invoke(beanObj,bean);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span>(value != <span class="literal">null</span> &amp;&amp; !<span class="string">&quot;&quot;</span>.equals(value)) &#123;</span><br><span class="line">                <span class="type">String</span> <span class="variable">methodName</span> <span class="operator">=</span> StringUtils.getSetterMethodNameByFieldName(propertyName);</span><br><span class="line">                <span class="type">Method</span> <span class="variable">method</span> <span class="operator">=</span> clazz.getMethod(methodName, String.class);</span><br><span class="line">                method.invoke(beanObj,value);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        singletonObjects.put(name,beanObj);</span><br><span class="line">        <span class="keyword">return</span> beanObj;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> &lt;T&gt; T <span class="title function_">getBean</span><span class="params">(String name, Class&lt;? extends T&gt; clazz)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line"></span><br><span class="line">        <span class="type">Object</span> <span class="variable">bean</span> <span class="operator">=</span> getBean(name);</span><br><span class="line">        <span class="keyword">if</span>(bean != <span class="literal">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> clazz.cast(bean);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<h3 id="745-自定义spring-ioc总结"><a class="markdownIt-Anchor" href="#745-自定义spring-ioc总结">#</a> 7.4.5 自定义 Spring IOC 总结</h3>
<h4 id="7451-使用到的设计模式"><a class="markdownIt-Anchor" href="#7451-使用到的设计模式">#</a> 7.4.5.1 使用到的设计模式</h4>
<ul>
<li>工厂模式。这个使用工厂模式 + 配置文件的方式。</li>
<li>单例模式。Spring IOC 管理的 bean 对象都是单例的，此处的单例不是通过构造器进行单例的控制的，而是 spring 框架对每一个 bean 只创建了一个对象。</li>
<li>模板方法模式。AbstractApplicationContext 类中的 finishBeanInitialization () 方法调用了子类的 getBean () 方法，因为 getBean () 的实现和环境息息相关。</li>
<li>迭代器模式。对于 MutablePropertyValues 类定义使用到了迭代器模式，因为此类存储并管理 PropertyValue 对象，也属于一个容器，所以给该容器提供一个遍历方式。</li>
</ul>
<p>spring 框架其实使用到了很多设计模式，如 AOP 使用到了代理模式，选择 JDK 代理或者 CGLIB 代理使用到了策略模式，还有适配器模式，装饰者模式，观察者模式等。</p>
<h4 id="7452-符合大部分设计原则"><a class="markdownIt-Anchor" href="#7452-符合大部分设计原则">#</a> 7.4.5.2 符合大部分设计原则</h4>
<h4 id="7453-整个设计和spring的设计还是有一定的出入"><a class="markdownIt-Anchor" href="#7453-整个设计和spring的设计还是有一定的出入">#</a> 7.4.5.3 整个设计和 Spring 的设计还是有一定的出入</h4>
<p>spring 框架底层是很复杂的，进行了很深入的封装，并对外提供了很好的扩展性。而我们自定义 SpringIOC 有以下几个目的：</p>
<ul>
<li>了解 Spring 底层对对象的大体管理机制。</li>
<li>了解设计模式在具体的开发中的使用。</li>
<li>以后学习 spring 源码，通过该案例的实现，可以降低 spring 学习的入门成本。</li>
</ul>

            </div>

            
                <div class="post-copyright-info">
                    <div class="article-copyright-info-container">
    <ul>
        <li><strong>标题:</strong> 设计模式</li>
        <li><strong>作者:</strong> meteor</li>
        <li><strong>创建于:</strong> 2023-06-05 17:12:30</li>
        
            <li>
                <strong>更新于:</strong> 2023-06-05 01:13:22
            </li>
        
        <li>
            <strong>链接:</strong> https://gitee.com/du-jinliang/2023/06/06/设计模式/
        </li>
        <li>
            <strong>版权声明:</strong> 本文章采用 <a class="license" target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">CC BY-NC-SA 4.0</a> 进行许可。
        </li>
    </ul>
</div>

                </div>
            

            
                <ul class="post-tags-box">
                    
                        <li class="tag-item">
                            <a href="/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">#设计模式</a>&nbsp;
                        </li>
                    
                </ul>
            

            

            
                <div class="article-nav">
                    
                        <div class="article-prev">
                            <a class="prev"
                            rel="prev"
                            href="/2023/06/19/Java%E6%9C%80%E4%BD%B3%E5%AE%9E%E8%B7%B5/"
                            >
                                <span class="left arrow-icon flex-center">
                                    <i class="fa-solid fa-chevron-left"></i>
                                </span>
                                <span class="title flex-center">
                                    <span class="post-nav-title-item">Java最佳实践</span>
                                    <span class="post-nav-item">上一篇</span>
                                </span>
                            </a>
                        </div>
                    
                    
                        <div class="article-next">
                            <a class="next"
                            rel="next"
                            href="/2023/06/06/%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95/"
                            >
                                <span class="title flex-center">
                                    <span class="post-nav-title-item">排序算法</span>
                                    <span class="post-nav-item">下一篇</span>
                                </span>
                                <span class="right arrow-icon flex-center">
                                    <i class="fa-solid fa-chevron-right"></i>
                                </span>
                            </a>
                        </div>
                    
                </div>
            


            
                <div class="comment-container">
                    <div class="comments-container">
    <div id="comment-anchor"></div>
    <div class="comment-area-title">
        <i class="fa-solid fa-comments"></i>&nbsp;评论
    </div>
    

        
            
    <div id="gitalk-container"></div>
    <script data-pjax
            src="//cdn.jsdelivr.net/npm/gitalk/dist/gitalk.min.js"></script>
    <script data-pjax>

        function loadGitalk() {
            let __gitalk__pathname = decodeURI(location.pathname);
            const __gitalk__pathnameLength = __gitalk__pathname.length;
            const __gitalk__pathnameMaxLength = 50;
            if (__gitalk__pathnameLength > __gitalk__pathnameMaxLength) {
                __gitalk__pathname = __gitalk__pathname.substring(0, __gitalk__pathnameMaxLength - 3) + '...';
            }

            try {
                Gitalk && new Gitalk({
                    clientID: '55bad54a77b7e60ad62d',
                    clientSecret: '1031c81500c6be06e338087cb7b713f2d0201b46',
                    repo: 'wait-you.github.io',
                    owner: 'wait-you',
                    admin: ['wait-you'],
                    id: 'comment',
                    language: 'zh-CN'
                }).render('gitalk-container');

            } catch (e) {
                window.Gitalk = null;
            }
        }

        if ('true') {
            const loadGitalkTimeout = setTimeout(() => {
                loadGitalk();
                clearTimeout(loadGitalkTimeout);
            }, 1000);
        } else {
            window.addEventListener('DOMContentLoaded', loadGitalk);
        }
    </script>



        
    
</div>

                </div>
            
        </div>

        
            <div class="toc-content-container">
                <div class="post-toc-wrap">
    <div class="post-toc">
        <div class="toc-title">此页目录</div>
        <div class="page-title">设计模式</div>
        <ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#1%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 1，设计模式</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#11-%E8%BD%AF%E4%BB%B6%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E7%9A%84%E4%BA%A7%E7%94%9F%E8%83%8C%E6%99%AF"><span class="nav-text"> 1.1 软件设计模式的产生背景</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#12-%E8%BD%AF%E4%BB%B6%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E7%9A%84%E6%A6%82%E5%BF%B5"><span class="nav-text"> 1.2 软件设计模式的概念</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#13-%E5%AD%A6%E4%B9%A0%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E7%9A%84%E5%BF%85%E8%A6%81%E6%80%A7"><span class="nav-text"> 1.3 学习设计模式的必要性</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#14-%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E5%88%86%E7%B1%BB"><span class="nav-text"> 1.4 设计模式分类</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#2uml%E5%9B%BE"><span class="nav-text"> 2，UML 图</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#21-%E7%B1%BB%E5%9B%BE%E6%A6%82%E8%BF%B0"><span class="nav-text"> 2.1 类图概述</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#22-%E7%B1%BB%E5%9B%BE%E7%9A%84%E4%BD%9C%E7%94%A8"><span class="nav-text"> 2.2 类图的作用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#23-%E7%B1%BB%E5%9B%BE%E8%A1%A8%E7%A4%BA%E6%B3%95"><span class="nav-text"> 2.3 类图表示法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#231-%E7%B1%BB%E7%9A%84%E8%A1%A8%E7%A4%BA%E6%96%B9%E5%BC%8F"><span class="nav-text"> 2.3.1 类的表示方式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#232-%E7%B1%BB%E4%B8%8E%E7%B1%BB%E4%B9%8B%E9%97%B4%E5%85%B3%E7%B3%BB%E7%9A%84%E8%A1%A8%E7%A4%BA%E6%96%B9%E5%BC%8F"><span class="nav-text"> 2.3.2 类与类之间关系的表示方式</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#3%E8%BD%AF%E4%BB%B6%E8%AE%BE%E8%AE%A1%E5%8E%9F%E5%88%99"><span class="nav-text"> 3，软件设计原则</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#31-%E5%BC%80%E9%97%AD%E5%8E%9F%E5%88%99"><span class="nav-text"> 3.1 开闭原则</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#32-%E9%87%8C%E6%B0%8F%E4%BB%A3%E6%8D%A2%E5%8E%9F%E5%88%99"><span class="nav-text"> 3.2 里氏代换原则</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#33-%E4%BE%9D%E8%B5%96%E5%80%92%E8%BD%AC%E5%8E%9F%E5%88%99"><span class="nav-text"> 3.3 依赖倒转原则</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#34-%E6%8E%A5%E5%8F%A3%E9%9A%94%E7%A6%BB%E5%8E%9F%E5%88%99"><span class="nav-text"> 3.4 接口隔离原则</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#35-%E8%BF%AA%E7%B1%B3%E7%89%B9%E6%B3%95%E5%88%99"><span class="nav-text"> 3.5 迪米特法则</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#36-%E5%90%88%E6%88%90%E5%A4%8D%E7%94%A8%E5%8E%9F%E5%88%99"><span class="nav-text"> 3.6 合成复用原则</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#4%E5%88%9B%E5%BB%BA%E5%9E%8B%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 4，创建型模式</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#41-%E5%8D%95%E4%BE%8B%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 4.1 单例设计模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#411-%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F%E7%9A%84%E7%BB%93%E6%9E%84"><span class="nav-text"> 4.1.1 单例模式的结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#412-%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F%E7%9A%84%E5%AE%9E%E7%8E%B0"><span class="nav-text"> 4.1.2 单例模式的实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#413-%E5%AD%98%E5%9C%A8%E7%9A%84%E9%97%AE%E9%A2%98"><span class="nav-text"> 4.1.3 存在的问题</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#414-jdk%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90-runtime%E7%B1%BB"><span class="nav-text"> 4.1.4 JDK 源码解析 - Runtime 类</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#42-%E5%B7%A5%E5%8E%82%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 4.2 工厂模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#421-%E6%A6%82%E8%BF%B0"><span class="nav-text"> 4.2.1 概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#422-%E7%AE%80%E5%8D%95%E5%B7%A5%E5%8E%82%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 4.2.2 简单工厂模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#423-%E5%B7%A5%E5%8E%82%E6%96%B9%E6%B3%95%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 4.2.3 工厂方法模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#424-%E6%8A%BD%E8%B1%A1%E5%B7%A5%E5%8E%82%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 4.2.4 抽象工厂模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#425-%E6%A8%A1%E5%BC%8F%E6%89%A9%E5%B1%95"><span class="nav-text"> 4.2.5 模式扩展</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#426-jdk%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90-collectioniterator%E6%96%B9%E6%B3%95"><span class="nav-text"> 4.2.6 JDK 源码解析 - Collection.iterator 方法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#43-%E5%8E%9F%E5%9E%8B%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 4.3 原型模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#431-%E6%A6%82%E8%BF%B0"><span class="nav-text"> 4.3.1 概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#432-%E7%BB%93%E6%9E%84"><span class="nav-text"> 4.3.2 结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#433-%E5%AE%9E%E7%8E%B0"><span class="nav-text"> 4.3.3 实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#434-%E6%A1%88%E4%BE%8B"><span class="nav-text"> 4.3.4 案例</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#435-%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="nav-text"> 4.3.5 使用场景</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#436-%E6%89%A9%E5%B1%95%E6%B7%B1%E5%85%8B%E9%9A%86"><span class="nav-text"> 4.3.6 扩展（深克隆）</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#45-%E5%BB%BA%E9%80%A0%E8%80%85%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 4.5 建造者模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#441-%E6%A6%82%E8%BF%B0"><span class="nav-text"> 4.4.1 概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#442-%E7%BB%93%E6%9E%84"><span class="nav-text"> 4.4.2 结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#443-%E5%AE%9E%E4%BE%8B"><span class="nav-text"> 4.4.3 实例</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#444-%E4%BC%98%E7%BC%BA%E7%82%B9"><span class="nav-text"> 4.4.4 优缺点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#445-%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="nav-text"> 4.4.5 使用场景</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#446-%E6%A8%A1%E5%BC%8F%E6%89%A9%E5%B1%95"><span class="nav-text"> 4.4.6 模式扩展</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#46-%E5%88%9B%E5%BB%BA%E8%80%85%E6%A8%A1%E5%BC%8F%E5%AF%B9%E6%AF%94"><span class="nav-text"> 4.6 创建者模式对比</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#461-%E5%B7%A5%E5%8E%82%E6%96%B9%E6%B3%95%E6%A8%A1%E5%BC%8Fvs%E5%BB%BA%E9%80%A0%E8%80%85%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 4.6.1 工厂方法模式 VS 建造者模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#462-%E6%8A%BD%E8%B1%A1%E5%B7%A5%E5%8E%82%E6%A8%A1%E5%BC%8Fvs%E5%BB%BA%E9%80%A0%E8%80%85%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 4.6.2 抽象工厂模式 VS 建造者模式</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#5%E7%BB%93%E6%9E%84%E5%9E%8B%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 5，结构型模式</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#51-%E4%BB%A3%E7%90%86%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 5.1 代理模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#511-%E6%A6%82%E8%BF%B0"><span class="nav-text"> 5.1.1 概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#512-%E7%BB%93%E6%9E%84"><span class="nav-text"> 5.1.2 结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#513-%E9%9D%99%E6%80%81%E4%BB%A3%E7%90%86"><span class="nav-text"> 5.1.3 静态代理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#514-jdk%E5%8A%A8%E6%80%81%E4%BB%A3%E7%90%86"><span class="nav-text"> 5.1.4 JDK 动态代理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#515-cglib%E5%8A%A8%E6%80%81%E4%BB%A3%E7%90%86"><span class="nav-text"> 5.1.5 CGLIB 动态代理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#516-%E4%B8%89%E7%A7%8D%E4%BB%A3%E7%90%86%E7%9A%84%E5%AF%B9%E6%AF%94"><span class="nav-text"> 5.1.6 三种代理的对比</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#517-%E4%BC%98%E7%BC%BA%E7%82%B9"><span class="nav-text"> 5.1.7 优缺点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#518-%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="nav-text"> 5.1.8 使用场景</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#52-%E9%80%82%E9%85%8D%E5%99%A8%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 5.2 适配器模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#521-%E6%A6%82%E8%BF%B0"><span class="nav-text"> 5.2.1 概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#522-%E7%BB%93%E6%9E%84"><span class="nav-text"> 5.2.2 结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#523-%E7%B1%BB%E9%80%82%E9%85%8D%E5%99%A8%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 5.2.3 类适配器模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#524-%E5%AF%B9%E8%B1%A1%E9%80%82%E9%85%8D%E5%99%A8%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 5.2.4 对象适配器模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#525-%E5%BA%94%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="nav-text"> 5.2.5 应用场景</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#526-jdk%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90"><span class="nav-text"> 5.2.6 JDK 源码解析</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#53-%E8%A3%85%E9%A5%B0%E8%80%85%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 5.3 装饰者模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#531-%E6%A6%82%E8%BF%B0"><span class="nav-text"> 5.3.1 概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#532-%E7%BB%93%E6%9E%84"><span class="nav-text"> 5.3.2 结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#533-%E6%A1%88%E4%BE%8B"><span class="nav-text"> 5.3.3 案例</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#534-%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="nav-text"> 5.3.4 使用场景</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#535-jdk%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90"><span class="nav-text"> 5.3.5 JDK 源码解析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#536-%E4%BB%A3%E7%90%86%E5%92%8C%E8%A3%85%E9%A5%B0%E8%80%85%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="nav-text"> 5.3.6 代理和装饰者的区别</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#54-%E6%A1%A5%E6%8E%A5%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 5.4 桥接模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#541-%E6%A6%82%E8%BF%B0"><span class="nav-text"> 5.4.1 概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#542-%E7%BB%93%E6%9E%84"><span class="nav-text"> 5.4.2 结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#543-%E6%A1%88%E4%BE%8B"><span class="nav-text"> 5.4.3 案例</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#544-%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="nav-text"> 5.4.4 使用场景</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#55-%E5%A4%96%E8%A7%82%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 5.5 外观模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#551-%E6%A6%82%E8%BF%B0"><span class="nav-text"> 5.5.1 概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#552-%E7%BB%93%E6%9E%84"><span class="nav-text"> 5.5.2 结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#553-%E6%A1%88%E4%BE%8B"><span class="nav-text"> 5.5.3 案例</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#554-%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="nav-text"> 5.5.4 使用场景</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#555-%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90"><span class="nav-text"> 5.5.5 源码解析</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#56-%E7%BB%84%E5%90%88%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 5.6 组合模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#561-%E6%A6%82%E8%BF%B0"><span class="nav-text"> 5.6.1 概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#562-%E7%BB%93%E6%9E%84"><span class="nav-text"> 5.6.2 结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#563-%E6%A1%88%E4%BE%8B%E5%AE%9E%E7%8E%B0"><span class="nav-text"> 5.6.3 案例实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#564-%E7%BB%84%E5%90%88%E6%A8%A1%E5%BC%8F%E7%9A%84%E5%88%86%E7%B1%BB"><span class="nav-text"> 5.6.4 组合模式的分类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#565-%E4%BC%98%E7%82%B9"><span class="nav-text"> 5.6.5 优点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#566-%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="nav-text"> 5.6.6 使用场景</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#57-%E4%BA%AB%E5%85%83%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 5.7 享元模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#571-%E6%A6%82%E8%BF%B0"><span class="nav-text"> 5.7.1 概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#572-%E7%BB%93%E6%9E%84"><span class="nav-text"> 5.7.2 结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#573-%E6%A1%88%E4%BE%8B%E5%AE%9E%E7%8E%B0"><span class="nav-text"> 5.7.3 案例实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#575-%E4%BC%98%E7%BC%BA%E7%82%B9%E5%92%8C%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="nav-text"> 5.7.5 优缺点和使用场景</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#576-jdk%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90"><span class="nav-text"> 5.7.6 JDK 源码解析</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#6%E8%A1%8C%E4%B8%BA%E5%9E%8B%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 6，行为型模式</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#61-%E6%A8%A1%E6%9D%BF%E6%96%B9%E6%B3%95%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 6.1 模板方法模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#611-%E6%A6%82%E8%BF%B0"><span class="nav-text"> 6.1.1 概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#612-%E7%BB%93%E6%9E%84"><span class="nav-text"> 6.1.2 结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#613-%E6%A1%88%E4%BE%8B%E5%AE%9E%E7%8E%B0"><span class="nav-text"> 6.1.3 案例实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#613-%E4%BC%98%E7%BC%BA%E7%82%B9"><span class="nav-text"> 6.1.3 优缺点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#614-%E9%80%82%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="nav-text"> 6.1.4 适用场景</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#615-jdk%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90"><span class="nav-text"> 6.1.5 JDK 源码解析</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#62-%E7%AD%96%E7%95%A5%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 6.2 策略模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#621-%E6%A6%82%E8%BF%B0"><span class="nav-text"> 6.2.1 概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#622-%E7%BB%93%E6%9E%84"><span class="nav-text"> 6.2.2 结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#623-%E6%A1%88%E4%BE%8B%E5%AE%9E%E7%8E%B0"><span class="nav-text"> 6.2.3 案例实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#624-%E4%BC%98%E7%BC%BA%E7%82%B9"><span class="nav-text"> 6.2.4 优缺点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#625-%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="nav-text"> 6.2.5 使用场景</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#626-jdk%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90"><span class="nav-text"> 6.2.6 JDK 源码解析</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#63-%E5%91%BD%E4%BB%A4%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 6.3 命令模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#631-%E6%A6%82%E8%BF%B0"><span class="nav-text"> 6.3.1 概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#632-%E7%BB%93%E6%9E%84"><span class="nav-text"> 6.3.2 结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#633-%E6%A1%88%E4%BE%8B%E5%AE%9E%E7%8E%B0"><span class="nav-text"> 6.3.3 案例实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#634-%E4%BC%98%E7%BC%BA%E7%82%B9"><span class="nav-text"> 6.3.4 优缺点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#635-%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="nav-text"> 6.3.5 使用场景</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#636-jdk%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90"><span class="nav-text"> 6.3.6 JDK 源码解析</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#64-%E8%B4%A3%E4%BB%BB%E9%93%BE%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 6.4 责任链模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#641-%E6%A6%82%E8%BF%B0"><span class="nav-text"> 6.4.1 概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#642-%E7%BB%93%E6%9E%84"><span class="nav-text"> 6.4.2 结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#643-%E6%A1%88%E4%BE%8B%E5%AE%9E%E7%8E%B0"><span class="nav-text"> 6.4.3 案例实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#644-%E4%BC%98%E7%BC%BA%E7%82%B9"><span class="nav-text"> 6.4.4 优缺点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#645-%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90"><span class="nav-text"> 6.4.5 源码解析</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#65-%E7%8A%B6%E6%80%81%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 6.5 状态模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#651-%E6%A6%82%E8%BF%B0"><span class="nav-text"> 6.5.1 概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#652-%E7%BB%93%E6%9E%84"><span class="nav-text"> 6.5.2 结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#653-%E6%A1%88%E4%BE%8B%E5%AE%9E%E7%8E%B0"><span class="nav-text"> 6.5.3 案例实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#654-%E4%BC%98%E7%BC%BA%E7%82%B9"><span class="nav-text"> 6.5.4 优缺点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#655-%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="nav-text"> 6.5.5 使用场景</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#66-%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 6.6 观察者模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#661-%E6%A6%82%E8%BF%B0"><span class="nav-text"> 6.6.1 概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#662-%E7%BB%93%E6%9E%84"><span class="nav-text"> 6.6.2 结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#663-%E6%A1%88%E4%BE%8B%E5%AE%9E%E7%8E%B0"><span class="nav-text"> 6.6.3 案例实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#664-%E4%BC%98%E7%BC%BA%E7%82%B9"><span class="nav-text"> 6.6.4 优缺点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#665-%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="nav-text"> 6.6.5 使用场景</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#666-jdk%E4%B8%AD%E6%8F%90%E4%BE%9B%E7%9A%84%E5%AE%9E%E7%8E%B0"><span class="nav-text"> 6.6.6 JDK 中提供的实现</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#67-%E4%B8%AD%E4%BB%8B%E8%80%85%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 6.7 中介者模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#671-%E6%A6%82%E8%BF%B0"><span class="nav-text"> 6.7.1 概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#672-%E7%BB%93%E6%9E%84"><span class="nav-text"> 6.7.2 结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#673-%E6%A1%88%E4%BE%8B%E5%AE%9E%E7%8E%B0"><span class="nav-text"> 6.7.3 案例实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#674-%E4%BC%98%E7%BC%BA%E7%82%B9"><span class="nav-text"> 6.7.4 优缺点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#675-%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="nav-text"> 6.7.5 使用场景</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#68-%E8%BF%AD%E4%BB%A3%E5%99%A8%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 6.8 迭代器模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#681-%E6%A6%82%E8%BF%B0"><span class="nav-text"> 6.8.1 概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#682-%E7%BB%93%E6%9E%84"><span class="nav-text"> 6.8.2 结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#683-%E6%A1%88%E4%BE%8B%E5%AE%9E%E7%8E%B0"><span class="nav-text"> 6.8.3 案例实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#684-%E4%BC%98%E7%BC%BA%E7%82%B9"><span class="nav-text"> 6.8.4 优缺点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#685-%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="nav-text"> 6.8.5 使用场景</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#686-jdk%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90"><span class="nav-text"> 6.8.6 JDK 源码解析</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#69-%E8%AE%BF%E9%97%AE%E8%80%85%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 6.9 访问者模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#691-%E6%A6%82%E8%BF%B0"><span class="nav-text"> 6.9.1 概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#692-%E7%BB%93%E6%9E%84"><span class="nav-text"> 6.9.2 结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#693-%E6%A1%88%E4%BE%8B%E5%AE%9E%E7%8E%B0"><span class="nav-text"> 6.9.3 案例实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#694-%E4%BC%98%E7%BC%BA%E7%82%B9"><span class="nav-text"> 6.9.4 优缺点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#695-%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="nav-text"> 6.9.5  使用场景</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#696-%E6%89%A9%E5%B1%95"><span class="nav-text"> 6.9.6 扩展</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#610-%E5%A4%87%E5%BF%98%E5%BD%95%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 6.10 备忘录模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#6101-%E6%A6%82%E8%BF%B0"><span class="nav-text"> 6.10.1 概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6102-%E7%BB%93%E6%9E%84"><span class="nav-text"> 6.10.2 结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6103-%E6%A1%88%E4%BE%8B%E5%AE%9E%E7%8E%B0"><span class="nav-text"> 6.10.3 案例实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6104-%E4%BC%98%E7%BC%BA%E7%82%B9"><span class="nav-text"> 6.10.4 优缺点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6105-%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="nav-text"> 6.10.5 使用场景</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#611-%E8%A7%A3%E9%87%8A%E5%99%A8%E6%A8%A1%E5%BC%8F"><span class="nav-text"> 6.11 解释器模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#6111-%E6%A6%82%E8%BF%B0"><span class="nav-text"> 6.11.1 概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6112-%E7%BB%93%E6%9E%84"><span class="nav-text"> 6.11.2 结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6113-%E6%A1%88%E4%BE%8B%E5%AE%9E%E7%8E%B0"><span class="nav-text"> 6.11.3 案例实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6114-%E4%BC%98%E7%BC%BA%E7%82%B9"><span class="nav-text"> 6.11.4 优缺点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6115-%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="nav-text"> 6.11.5 使用场景</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#7%E8%87%AA%E5%AE%9A%E4%B9%89spring%E6%A1%86%E6%9E%B6"><span class="nav-text"> 7，自定义 Spring 框架</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#71-spring%E4%BD%BF%E7%94%A8%E5%9B%9E%E9%A1%BE"><span class="nav-text"> 7.1 spring 使用回顾</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#72-spring%E6%A0%B8%E5%BF%83%E5%8A%9F%E8%83%BD%E7%BB%93%E6%9E%84"><span class="nav-text"> 7.2 spring 核心功能结构</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#711-bean%E6%A6%82%E8%BF%B0"><span class="nav-text"> 7.1.1 bean 概述</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#73-spring-ioc%E7%9B%B8%E5%85%B3%E6%8E%A5%E5%8F%A3%E5%88%86%E6%9E%90"><span class="nav-text"> 7.3 Spring IOC 相关接口分析</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#731-beanfactory%E8%A7%A3%E6%9E%90"><span class="nav-text"> 7.3.1 BeanFactory 解析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#732-beandefinition%E8%A7%A3%E6%9E%90"><span class="nav-text"> 7.3.2 BeanDefinition 解析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#733-beandefinitionreader%E8%A7%A3%E6%9E%90"><span class="nav-text"> 7.3.3 BeanDefinitionReader 解析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#734-beandefinitionregistry%E8%A7%A3%E6%9E%90"><span class="nav-text"> 7.3.4 BeanDefinitionRegistry 解析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#735-%E5%88%9B%E5%BB%BA%E5%AE%B9%E5%99%A8"><span class="nav-text"> 7.3.5 创建容器</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#74-%E8%87%AA%E5%AE%9A%E4%B9%89springioc"><span class="nav-text"> 7.4 自定义 SpringIOC</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#741-%E5%AE%9A%E4%B9%89bean%E7%9B%B8%E5%85%B3%E7%9A%84pojo%E7%B1%BB"><span class="nav-text"> 7.4.1 定义 bean 相关的 pojo 类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#742-%E5%AE%9A%E4%B9%89%E6%B3%A8%E5%86%8C%E8%A1%A8%E7%9B%B8%E5%85%B3%E7%B1%BB"><span class="nav-text"> 7.4.2 定义注册表相关类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#743-%E5%AE%9A%E4%B9%89%E8%A7%A3%E6%9E%90%E5%99%A8%E7%9B%B8%E5%85%B3%E7%B1%BB"><span class="nav-text"> 7.4.3 定义解析器相关类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#744-ioc%E5%AE%B9%E5%99%A8%E7%9B%B8%E5%85%B3%E7%B1%BB"><span class="nav-text"> 7.4.4 IOC 容器相关类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#745-%E8%87%AA%E5%AE%9A%E4%B9%89spring-ioc%E6%80%BB%E7%BB%93"><span class="nav-text"> 7.4.5 自定义 Spring IOC 总结</span></a></li></ol></li></ol></li></ol>

    </div>
</div>
            </div>
        
    </div>
</div>


                

            </div>
            
            

        </div>

        <div class="main-content-footer">
            <footer class="footer">
    <div class="info-container">
        <div class="copyright-info">
            &copy;
            
              <span>2022</span>
              -
            
            2023&nbsp;&nbsp;<i class="fa-solid fa-heart fa-beat" style="--fa-animation-duration: 0.5s; color: #f54545"></i>&nbsp;&nbsp;<a href="/">meteor</a>
        </div>
        
            <script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
            <div class="website-count info-item">
                
                    <span id="busuanzi_container_site_uv" class="busuanzi_container_site_uv">
                        访问人数&nbsp;<span id="busuanzi_value_site_uv" class="busuanzi_value_site_uv"></span>
                    </span>
                
                
                    <span id="busuanzi_container_site_pv" class="busuanzi_container_site_pv">
                        总访问量&nbsp;<span id="busuanzi_value_site_pv" class="busuanzi_value_site_pv"></span>
                    </span>
                
            </div>
        
        <div class="theme-info info-item">
            <span class="powered-by-container">由 <?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg version="1.1" id="圖層_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="1rem" height="1rem" viewBox="0 0 512 512" enable-background="new 0 0 512 512" xml:space="preserve"><path fill="#0E83CD" d="M256.4,25.8l-200,115.5L56,371.5l199.6,114.7l200-115.5l0.4-230.2L256.4,25.8z M349,354.6l-18.4,10.7l-18.6-11V275H200v79.6l-18.4,10.7l-18.6-11v-197l18.5-10.6l18.5,10.8V237h112v-79.6l18.5-10.6l18.5,10.8V354.6z"/></svg><a target="_blank" href="https://hexo.io">Hexo</a> 驱动</span>
                <br>
            <span class="theme-version-container">主题&nbsp;<a class="theme-version" target="_blank" href="https://github.com/EvanNotFound/hexo-theme-redefine">Redefine v2.1.4</a>
        </div>
        
            <div class="icp-info info-item"><a target="_blank" rel="nofollow" href="
                
                    beian.miit.gov.cn
                
                ">冀ICP备20010108号</a></div>
        
        
        
            <div id="start_div" style="display:none">
                2022/8/17 11:45:14
            </div>
            <div>
                博客已运行 <span class="odometer" id="runtime_days" ></span> 天 <span class="odometer" id="runtime_hours"></span> 小时 <span class="odometer" id="runtime_minutes"></span> 分钟 <span class="odometer" id="runtime_seconds"></span> 秒
            </div>
        
        
        
            <script async data-pjax>
                try {
                    function odometer_init() {
                    const elements = document.querySelectorAll('.odometer');
                    elements.forEach(el => {
                        new Odometer({
                            el,
                            format: '( ddd).dd',
                            duration: 200
                        });
                    });
                    }
                    odometer_init();
                } catch (error) {}
            </script>
        
        
        
    </div>  
</footer>
        </div>
    </div>

    
        <div class="post-tools">
            <div class="post-tools-container">
    <ul class="article-tools-list">
        <!-- TOC aside toggle -->
        
            <li class="right-bottom-tools page-aside-toggle">
                <i class="fa-regular fa-outdent"></i>
            </li>
        

        <!-- go comment -->
        
            <li class="go-comment">
                <i class="fa-regular fa-comments"></i>
            </li>
        
    </ul>
</div>

        </div>
    

    <div class="right-side-tools-container">
        <div class="side-tools-container">
    <ul class="hidden-tools-list">
        <li class="right-bottom-tools tool-font-adjust-plus flex-center">
            <i class="fa-regular fa-magnifying-glass-plus"></i>
        </li>

        <li class="right-bottom-tools tool-font-adjust-minus flex-center">
            <i class="fa-regular fa-magnifying-glass-minus"></i>
        </li>

        <li class="right-bottom-tools tool-expand-width flex-center">
            <i class="fa-regular fa-expand"></i>
        </li>

        <li class="right-bottom-tools tool-dark-light-toggle flex-center">
            <i class="fa-regular fa-moon"></i>
        </li>

        <!-- rss -->
        

        

        <li class="right-bottom-tools tool-scroll-to-bottom flex-center">
            <i class="fa-regular fa-arrow-down"></i>
        </li>
    </ul>

    <ul class="visible-tools-list">
        <li class="right-bottom-tools toggle-tools-list flex-center">
            <i class="fa-regular fa-cog fa-spin"></i>
        </li>
        
            <li class="right-bottom-tools tool-scroll-to-top flex-center">
                <i class="arrow-up fas fa-arrow-up"></i>
                <span class="percent"></span>
            </li>
        
        
    </ul>
</div>

    </div>

    <div class="image-viewer-container">
    <img src="">
</div>


    


</main>




<script src="/js/utils.js"></script>

<script src="/js/main.js"></script>

<script src="/js/layouts/navbarShrink.js"></script>

<script src="/js/tools/scrollTopBottom.js"></script>

<script src="/js/tools/lightDarkSwitch.js"></script>





    
<script src="/js/tools/codeBlock.js"></script>




    
<script src="/js/layouts/lazyload.js"></script>




    
<script src="/js/tools/runtime.js"></script>

    
<script src="/js/layouts/odometer.min.js"></script>

    
<link rel="stylesheet" href="/assets/odometer-theme-minimal.css">




  
<script src="/js/libs/Typed.min.js"></script>

  
<script src="/js/plugins/typed.js"></script>







<div class="post-scripts pjax">
    
        
<script src="/js/tools/tocToggle.js"></script>

<script src="/js/libs/anime.min.js"></script>

<script src="/js/layouts/toc.js"></script>

<script src="/js/plugins/tabs.js"></script>

    
</div>


    
<script src="/js/libs/pjax.min.js"></script>

<script>
    window.addEventListener('DOMContentLoaded', () => {
        window.pjax = new Pjax({
            selectors: [
                'head title',
                '.page-container',
                '.pjax',
            ],
            history: true,
            debug: false,
            cacheBust: false,
            timeout: 0,
            analytics: false,
            currentUrlFullReload: false,
            scrollRestoration: false,
            // scrollTo: true,
        });

        document.addEventListener('pjax:send', () => {
            Global.utils.pjaxProgressBarStart();
        });

        document.addEventListener('pjax:complete', () => {
            Global.utils.pjaxProgressBarEnd();
            window.pjax.executeScripts(document.querySelectorAll('script[data-pjax], .pjax script'));
            Global.refresh();
        });
    });
</script>




</body>
</html>
